I'm trying to change src of an image with JS . I want to take the data attribute of another element and to place it on the src of the image:
This is the JS:
$(".color-click").click(function() {
var selected = $('.color-click');
var piccolor1 = selected.attr('data-pic1');
$('#products-products-small').attr('src', piccolor1);
});
This is this is the element of the data attribute:
<button data-pic1="images\logo.ppg" id="circle" class="color-click"> </button>
This is the picture with the src that I want to change :
<img src="images/logo22.png" data-name="" class="products-products-small clicked-prod num1" id="products-products-small" onclick="showImage('<?php product_image1_products() ?>');" alt="header_bg">
data-pic1value, and also you should usevar selected = $(this);, otherwise it will refer to a collection of nodes.$(this)instead of$('.color-click');and try usingselected.data('pic1');instead ofselected.attr('data-pic1');and your directory separator is backwards (should bedata-pic1="images/logo.ppg") also, you probably meantpnginstead ofppg..attr('data-pic1')works just fine, the problem can't be fixed by using.data('pic1')as they are functionally equivalent..color-clickthen usingthiswon't solve the problem either. just noting general improvements, you noted the problem in your first comment so i didn't bother writing an answer.