Simple Image Navigation Rollover in JQuery
by David
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<ul class="nav">
<li><a id="nav1"></a></li>
<li><a id="nav2"></a></li>
<li><a id="nav3"></a></li>
</ul>
CSS
.nav li {
display: inline-block;
margin: 0;
padding: 0;
}
.nav a {
display: inline-block;
cursor: pointer;
height: 43px;
}
#nav1 {
background: url('https://googledrive.com/host/0B6JoOY-U2ZgaWHZnLVM0LXJsdXc/tab_help.jpg') no-repeat;
width: 93px;
}
#nav1:hover {
background: url('https://googledrive.com/host/0B6JoOY-U2ZgaWHZnLVM0LXJsdXc/tab_help_over.jpg') no-repeat;
width: 93px;
}
#nav2 {
background: url('https://googledrive.com/host/0B6JoOY-U2ZgaWHZnLVM0LXJsdXc/tab_product_info.jpg') no-repeat;
width: 91px;
}
#nav2:hover {
background: url('https://googledrive.com/host/0B6JoOY-U2ZgaWHZnLVM0LXJsdXc/tab_product_info_over.jpg') no-repeat;
width: 91px;
}
#nav3 {
background: url('https://googledrive.com/host/0B6JoOY-U2ZgaWHZnLVM0LXJsdXc/tab_ship_pay.jpg') no-repeat;
width: 90px;
}
#nav3:hover {
background: url('https://googledrive.com/host/0B6JoOY-U2ZgaWHZnLVM0LXJsdXc/tab_ship_pay_over.jpg') no-repeat;
width: 90px;
}
JavaScript
$(document).ready(function() {
// Click Event
$('.nav a').click(function() {
// Grab value of id attribute
var $id = $(this).prop('id');
// Find the id dynamically and find the current bg image of the hover state
var $hov = $('#' + $id + ':hover').css('background-image');
// Set an inline style with the hover state's bg
$('#' + $id).attr('style', 'background-image: ' + $hov).addClass('selected');
// After selecting a new tab, iterate through prior tabs and remove their bg images
$('.nav li').find('a').each(function() {
if ($(this).prop('id') != $id ) {
$(this).removeAttr('style').removeClass('selected');
}
});
});
});