I’m currenty trying to create a nice nested navigation menu. The problem I face is that I want to make some elements change in a different way each time it is clicked.
I don’t really gasp how the DOM Tree respects my provious manipulations via Jquery…for example if i set a new class for a clicked element via the attr() function I’m not able to select the newly changed element with its class atribute.
Maybe I’m totally on the wrong track and this approch is wrong or must be tought in a different way. I would be so happy to hear from more experienced people how they make consecutive manipulaions on elements.
Here is what i try to achive: 1.) Trun it blue when clicked, 2.) turn it red when clicked again.
Here is a fiddle for this: http://jsfiddle.net/YsQTL/
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
*//First time clicked--> this works*
$("h1").click(function() {
$('h1').css({"color":"blue"}).attr('class','clicked').text('I should turn red if clicked again');
});
*//Second time clicked with added class "clicked"--> this doesn't work....why?*
$(".clicked").click(function() {
$('h1').css({"color":"red"})
});
});
</script>
</head>
<body>
<div id ="navigation">
<h1>Title to be changed to blue if clicked</h1>
</div>
</body>
</html>
The biggest problem is that you are binding the second event to elements that responds to the selector
.clickedon page load, that is to say, none.Instead, you could do something like this:
This will bind the event to all elements responding to the selector
"h1", i.e. all your h1 tags present on the page at page-load, and inside the event handler, we check if the element has the class.Also, keep in mind that since you were using the selector
$("h1")instead of$(this)inside your event handler, every single h1 element on the page would get updated by your code, instead of just the one you actually clicked.Fiddle: http://jsfiddle.net/YsQTL/3/