Can anyone please explain me why this code does what it does.
What I would like to achieve is that when the first button gets clicked javascript adds a disabled class to the second button and when the second button gets pressed with disabled class the javascript won’t run.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery question</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<style>
a.success { background: green }
</style>
</head>
<body>
<div id="holder">
<a href="#" class="button">Button 1</a>
<a href="#" class="button">Button 2</a>
</div>
</body>
<script>
$(function(){
$('#holder a.button:not(.disabled)').on('click', function() {
// Toggle success class
if($(this).hasClass('success')) {
$(this).removeClass('success');
}
else {
$(this).addClass('success');
}
// Add disabled class to the not so lucky button
$('#holder a.button:not(.success)').each(function() {
$(this).addClass('disabled');
});
});
});
</script>
</html>
Looking at the console this is not the case. Even though the second button gets the disabled class. Pressing the disabled button still runs javascript despite the :not(.disabled) selector.
It behaves as expected when I change it like this
$('#holder a.button').on('click', function() {
if($(this).hasClass('disabled')) {
return false;
}
But could someone please explain why it’s acting like that?
The selector is not going to dynamically re-evaluate itself every time an event is fired.
The best way to solve this problem would be to use event delegation: