Reputation: 51
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">
Upvotes: 0
Views: 129
Reputation: 851
Is this what you're looking for ?
$(function(){
// image element
var target = $(".products-products-small.num1");
// when button is clicked
$(".color-click").on("click", function(){
// get image
var src = $(this).data("img-src");
// set image
$(target).attr("src", src);
});
});
https://jsfiddle.net/fatgamer85/ta90wt33/2/
Upvotes: 0
Reputation: 66093
Because you are using a backslash \
instead of a forward slash /
in the data-pic1
value (check the file path if it actually points to an actual image), and also you should use var selected = $(this);
, otherwise it will refer to a collection of nodes. $(this)
in the event handler ensures that you are referring to the actual element that triggered the event, instead of returning a collection of elements.
Here is a proof-of-concept that works:
$(function() {
$(".color-click").click(function() {
var selected = $(this);
var piccolor1 = selected.attr('data-pic1');
$('#products-products-small').attr('src', piccolor1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-pic1="http://via.placeholder.com/350x150/B13131/FFF" id="circle" class="color-click"> Click me to change image</button>
<img src="http://via.placeholder.com/350x150/" data-name="" class="products-products-small clicked-prod num1" id="products-products-small" alt="header_bg">
Upvotes: 1