I have a really strange problem with this code:
In this Fiddle it alert’s that “red” has index of 0 (which I want to alert), but on my local computer it alert’s that check is not working…
Can someone tell me why is this happening?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
<meta name="author" content="Dejan Peic"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<style type="text/css">
.wrapper{
width:100px;
height:150px;
border:1px solid #000000;
margin:0auto;
position:relative;
display:block;
}
.red{
width:100px;
height:50px;
display:block;
background-color:red;
}
.blue{
width:100px;
height:50px;
display:block;
background-color:blue;
}
.green{
width:100px;
height:50px;
display:block;
background-color:green;
}
.checkIndex{
width:150px;
height:20px;
background-color:black;
color:white;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var red = $('.red');
var active = $('.active');
var redIndex = red.index();
var activeIndex = active.index();
$(document).ready(function(){
$('.wrapper div:last').addClass('active');
$('.checkIndex').click(function(){
if(redIndex > activeIndex){
alert('Red has index 0');
}
else{
alert('check doesnt work :(');
}
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
</div><!--/wrapper-->
<div class="checkIndex">Check index of RED</div>
</body>
</html>
You need to move these lines:
inside of your
$(document).ready(...)function.Outside of that function the specified DOM elements don’t exist yet.
It only works on jsfiddle because by default that site automatically wraps your code in an
onloadhandler, which achieves the same effect.