Reputation:
On load of the page, I'm creating horizontal tabs in Jquery using:
function createhorizontaltab(categories) {
var categoryArr = JSON.parse(categories);
var htmlbuild = $('<ul>');
for (var i = 0; i < categoryArr.categories.length; i++) {
var name = categoryArr.categories[i].name;
htmlbuild.append('<li id= "'+name+'" class="active">'+name+'</a></li>');
}
htmlbuild.append('</ul>');
$("#menuInner").append(htmlbuild);
}
my HTML code:
<body>
<section class="menuWrap">
<div id = "menuInner" class="menuInner">
</div>
</section>
</body>
I'm trying to register with the click event of li selected this way, but this is not getting fire up.
I need to keep this outside the Jquery ready() function:
$(document).ready(function () {
createhorizontaltab(categories)
}
$("#menuInner li ").click(function(){
}
Could anybody help me with this?
Upvotes: 0
Views: 144
Reputation: 8171
You are trying to add event handler when on page load, but the li
is not exist on page that time.
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
So, you must use Event delegation
The event is dispatched to its target EventTarget and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the EventTarget's parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including the Document.
$(document).on( "click", "#menuInner li", function() {
// your code
});
Upvotes: 0
Reputation: 20636
Use this,
$(document).on( "click", "#menuInner li", function() {
//
});
on() - Event delegation
Or
$(document).delegate( "#menuInner li", "click", function() {
//
});
delegate() - Attaches a handler to one or more events for elements specified in the selector, now or in the future.
And you were appending elements dynamically.
Upvotes: 3