0

There is my code which adds class 'nav-pills' to element with class 'nav-tabs' when window width is lower than 768px.

$(window).on('resize', function () {
$('.nav-tabs').toggleClass('nav-pills', $(window).width() < 768);
});

I want to alert something when user click link inside DOM element with these 2 classes (nav-tabs and nav-pills). But nothing happend.

$(".nav-tabs.nav-pills a").click(function(){
    alert('test');
});

jQuery toggleClass works fine and add 'nav-pills' to 'nav-tabs' element (I checked it in chrome inspector), but alert wont work.

Anyone can help me?

verdun3r
  • 71
  • 2
  • 9
  • I *really* recommend to read the jQuery tutorial: *"It is important to note that .on() can only create event listeners on elements that **exist at the time you set up the listeners**."* (http://learn.jquery.com/events/event-basics/) – Felix Kling Mar 03 '15 at 16:11
  • Hu Barmar ? This is a strange choice for closing as duplicate... – Denys Séguret Mar 03 '15 at 16:13

1 Answers1

0

The problem you have is that the bind is done once, before the nav-pills class is added. So you're binding to an empty set.

You could bind on ".nav-tabs a" and test in the callback if there's an element in $(this).closest(".nav-tabs.nav-pills") but a cleaner solution would be to use on and delegation :

$(document).on("click", ".nav-tabs.nav-pills a", function(){
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758