I have several div’s on my page. See example http://jsfiddle.net/AYRh6/26/
When I’m trying to transfer this code to my asp.net mvc3 project it looks like:
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
<script src="@Url.Content("/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$('.tab').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
</script>
</head>
<body>
<div class="main">
<div class="tab" style="float:right;">Tab 3</div>
<div class="tab" style="float:right;">Tab 2</div>
<div class="tab active" style="float:right;">Tab 1</div>
</div>
</body>
</html>
CSS:
.main{
width:325px;
}
div.tab {
background: white;
width: 100px;
border: 1px solid grey;
padding-left:5px;
}
div.tab.active {
background: blue;
}
div.tab:hover {
background: aqua;
}
As you can see javascript is located at the header of html page. It doesn’t work for me.
I was trying to set this script for onclick event like:
<div class="tab" style="float:right;" onclick="$(this).addClass('active').siblings().removeClass('active');">Tab 3</div>
<div class="tab" style="float:right;" onclick="$(this).addClass('active').siblings().removeClass('active');">Tab 2</div>
<div class="tab active" style="float:right;" onclick="$(this).addClass('active').siblings().removeClass('active');">Tab 1</div>
It’s work fine! What I’m doing wrong when this script located at the header?
The Javascript code is executed immediately but the elements that you want to attach the handlers to haven’t been put into the DOM yet. You can use .ready in jQuery or put your script at the bottom of the document:
If you use a debugger and set a breakpoint at
$('.tab').clickin your code you’ll notice that$('.tab')returns an empty array of elements.