Reputation: 523
please see the code .
$(".test").on("click", function() {
var sclass = $(this).attr("class").split(" ")[1];
$(".color").trigger("click");
$(".color").on("change", function() {
var scolor = $(this).val();
$("." + sclass).css("background-color", scolor);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="color" name="color" class="color"><br><br>
<div class="test test1">hii</div><br><br>
<div class="test test2">hello</div>
here i need to change the background color of the div by selecting color . But when i am selecting color for one div then this color is effected to two ? what is the error in this code ?
Upvotes: 1
Views: 372
Reputation: 3509
You should use off and then on
$(".test").on("click", function() {
var $el=$(this);
$(".color").off("change").on("change", function() {
$el.css("background-color", $(this).val());
}).click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="color" name="color" class="color"><br><br>
<div class="test test1">hii</div><br><br>
<div class="test test2">hello</div>
Upvotes: 1
Reputation: 448
In order to understand this bug, you will need to understand Javascript closures. There's a good link here that explains it, and it reveals this is a pretty easy mistake to make (link to MDN closures).
You're creating closures when you assign these functions to those events , and each closure shares the same environment. Essentially sclass
will be equal to test test2
regardless. You're selection in $("." + sclass)
will expand to $(.test test2)
. Also you may need to include quotes in your jQuery selection.
Upvotes: 1
Reputation: 337580
The problem you have is because you add a new change
handler to the color input on each click. This means the first handler is attached to the .test1
element when you create a new one on .test2
. This is why both elements are then effected by the change.
You need to move the change
handler outside of the click
handler. You can then just store the reference of the element directly instead of a class. Try this:
$(".test").on("click", function() {
$(".color").data('el', $(this)).trigger("click");
});
$(".color").on("change", function() {
var $el = $(this).data('el');
$el && $el.css("background-color", this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="color" name="color" class="color"><br><br>
<div class="test test1">hii</div><br><br>
<div class="test test2">hello</div>
Upvotes: 0