I have started to learn jQuery and am going through some very simple examples but have run into problems already. I am changing the body upon the click of a day button and again a different background for a night button.
What I am finding is that the click handler is only working once an if I click the night button first then the day button won’t work? Can anyone advise or share a best practice with this?
Here is the code I have so far:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h1>My Website</h1>
<button id="first">Day</button>
<button id="second">Night</button>
<script>
$(function() {
$('button#first').click(function() {
$('body').addClass('day');
});
debud
$('button#second').click(function() {
$('body').addClass('night');
});
});
</script>
</body>
</html>
Runnable copy at http://jsbin.com/ufadul/3/edit
This script will continue adding these classes to your body tag instead of replacing them.
.nightis taking priority over.daybecause of the position in the CSS.Use the following to prevent this from happening: