Reputation: 37
On my website I have a jQuery script that replaces the content of a div with HTML from another file when a button is clicked. Each button has an ID that is identical to the filename of the HTML document that gets replaced in the div.
On the homepage all of the buttons work when clicked and the content gets replaced. However, when I try to click one of the new buttons to replace the content again nothing happens. Any idea why it will not execute twice?
// JavaScript Document
$( document ).ready(function() {
$('.button').click(function(e) {
e.preventDefault(); // Stops the browser from following the href in the <a>
var that = $(this)
, id = that.attr('id')
, url = 'questions/' + id + '.html'
;
$.post(url, function(data) {
$('#replace').html(data); // Display external file to target div
window.scrollTo(0, 0); // Forces a scroll back to the top of the page
});
});
});
Upvotes: 0
Views: 74
Reputation: 36438
Assuming the .button
elements are part of the HTML being replaced, the new elements won't have handlers attached. You'll want to attach your handler to the body instead, filtered by the button
class:
$(document).on('click', '.button', function(e) {
e.preventDefault(); // Stops the browser from following the href in the <a>
var that = $(this)
, id = that.attr('id')
, url = 'questions/' + id + '.html'
;
$.post(url, function(data) {
$('#replace').html(data); // Display external file to target div
window.scrollTo(0, 0); // Forces a scroll back to the top of the page
});
});
Upvotes: 2