Reputation: 2174
i have a div where i am running a for loop. Which is creating the below divs based on the number of rows in the fields.
<div class="parent">
<p style=" font-family: Times New Roman;color:#a0a0a0; ">
Content 1 goes here.........
</p>
<div class="child">
<span> <a class="likebtn">Like</a> </span>1 people like this
</div>
<hr/>
</div>
the above shown div is in a for-each loop i.e creating multiple divs same like this with different content on it.
Now i am trying to call my jquery function , if users click on any like button residing into the div. I tried the below function but my function is not getting call. Please help me , why regarding this issue.
<script type="text/javascript">
$('.parent .child .likebtn').click(function(e)
{
alert("function called");
});
</script>
And one thing,div's are created dynamically, if i write my above javascript code just after my for-each loop then my function is getting called. It's not good practice to write javascript function in Controller. I am using COdeigniter framework. Plase help me, i have to specify this function either in head or body
Upvotes: 2
Views: 216
Reputation: 1111
Wrap your function in enclosure to make sure it gets executed after your DOM has fully loaded like so:
$(function() {
$('.parent .child .likebtn').click(function(e) {
alert("function called");
});
});
EDIT: Are you loading this content from AJAX? In this case you need to use the .on() function to make sure new dom elements get the events, syntax somethign like this: $(document).on(events, selector, data, handler); -> api.jquery.com/on
EDIT 2: Same answer as tymeJV
Upvotes: 1
Reputation: 104795
If the div's are created dynamically, call them like
$(document).on('click', '.parent .child .likebtn', function(e)
{
alert("function called");
});
Upvotes: 5