I want to turn the JavaScript in this example into jQuery.
Basically I’ve jerry-rigged two scripts together. One is jQuery; creates the “active” function. But the hide/display layer function is in Javascript, and there’s too much code for my liking, I’m thinking it must be possible to cut it down into something simple and effective with jQuery.
FYI, I just started out with Javascript and jQuery.
Help?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSMenu</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
function HideLayer(d) { document.getElementById(d).style.display = "none"; }
function DisplayLayer(d) { document.getElementById(d).style.display = "block"; };
$(function() {
$('div.menuitem').click(function() {
var $this = $(this);
$('.active').removeClass('active');
$this.addClass('active');
})
});
</script>
<style>
#menuholder {width:100px; float:left; border-bottom:solid thin #000;}
.menuitem {border-top:solid thin #000; border-left:solid thin #000; border-right:solid thin #000;}
.menuitem:hover {cursor:pointer; color:#555}
.active {font-weight:bold; color:#000}
.active:hover {color:#000}
#layerholder {float:left; margin-left:20px; width:50px; height:50px; border:solid thin;}
.layer {padding-left:3px; font-size:36px; display:none;}
</style>
</head>
<body>
<div id="menuholder">
<div onClick="DisplayLayer('firstLayer');HideLayer('secondLayer');HideLayer('thirdLayer');HideLayer('fourthLayer')" class="menuitem">Item 1</div>
<div onClick="HideLayer('firstLayer');HideLayer('thirdLayer');HideLayer('fourthLayer');DisplayLayer('secondLayer')" class="menuitem">Item 2</div>
<div onClick="HideLayer('firstLayer');HideLayer('secondLayer');HideLayer('fourthLayer');DisplayLayer('thirdLayer')" class="menuitem">Item 3</div>
<div onClick="HideLayer('firstLayer');HideLayer('secondLayer');HideLayer('thirdLayer');DisplayLayer('fourthLayer')" class="menuitem">Item 4</div>
</div>
<div id="layerholder">
<div class="layer" id="firstLayer">1</div>
<div class="layer" id="secondLayer">2</div>
<div class="layer" id="thirdLayer">3</div>
<div class="layer" id="fourthLayer">4</div>
</div>
<div style="clear:both;"></div>
</body>
</html>
You could change your HTML to:
And then use this jQuery:
This also not 100% perfect as
relis not a valid attribute fordivelements. You should consider changing thedivs toaelements (and use thehrefattribute) which has the benefit that the browser also jumps to the linked element.DEMO
Update: If you decide to go with links, it would be:
and