0

I have a problem with my javascript function :

$(".like-btn").click(function () { .. }

this function is not triggered anymore after in my javascript somewhere else I do stuff like

 $("#1021").append("'<button type="submit" class="btn btn-default like-btn" ... .etc ");

So basically I need my jquery to be triggered also after I add some more html on my page.

1

1 Answer 1

4

Since the like-btn class is added dynamically, you need to use event delegation to register the event handler like this:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#1021').on('click', '.like-btn', function(event) {
    event.preventDefault();
    alert('testlink'); 
});
Sign up to request clarification or add additional context in comments.

3 Comments

The 1021 was just an example, the id changes :)
If the ID is changing that you provided for the example, you need to traverse up the DOM to the first static element available and use that as your selector. The above answer is correct, but you need to get the first parent element that isn't dynamic then.
Then you can use document instead. But, it would be better to use a parent static container. That would attach your event to any like-btn within the container element, reducing the scope of having to check the whole document element tree and increasing efficiency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.