Reputation: 19
Appended images used as buttons to show/hide content below a heading:
<!DOCTYPE html>
<html>
<body>
<h2>
the heading
</h2>
<p>
the content
</p>
</body>
</html>
$(document).ready(function () {
var $imag = $("<img src='arrow_down.jpg'>");
var $imag2 = $("<img src='arrow_up.jpg'>");
$("h2").append($imag);
$($imag).on("click", function(){
$("p").hide();
($imag).remove();
$("h2").append($imag2);
});
$($imag2).on("click", function () {
$("p").show();
($imag2).remove();
$("h2").append($imag);
});
});
$(document).main(ready);
At first the images work when clicked. but the next time you click it, it doesn't without having to refresh the page. Why?
Upvotes: 0
Views: 1915
Reputation: 11416
This is because event handlers like click() have to be appended to elements that are already in the DOM when the page is loaded. For elements that are added later the event has to be delegated from a static parent element using on(), like:
$(document).on("click", $imag, function(){
$("p").hide();
($imag).remove();
$("h2").append($imag2);
});
$(document).on("click", $imag2, function () {
$("p").show();
($imag2).remove();
$("h2").append($imag);
});
Just added a Fiddle with an adjustment as I wasn't sure if this would work with the variables $imag / $imag2 (it doesn't). Instead you should just add classes to your images, e.g. like this:
var $imag = $("<img class='down' src='arrow_down.jpg'>");
var $imag2 = $("<img class='up' src='arrow_up.jpg'>");
with adjusted code
$(document).on("click", '.down', function(){
$("p").hide();
$('.down').remove();
$("h2").append($imag2);
});
$(document).on("click", '.up', function () {
$("p").show();
$('.up').remove();
$("h2").append($imag);
});
For reference: https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
Upvotes: 3