Reputation: 1
My jQuery code looks like this:
$(document).ready(function() { //load the index page into a div container
//set a bottom (border) line under the item of navigation bar
$('#siteloader').load('empleados.jsp');
$('ul#menu li a.active').css({"borderbottom": "4px solid"});
//When the hyperlink is clicked
// set the right color to the item of the navigation bar
$('ul#menu li a').click(function() {
var page = $(this).attr('href');
if (page !== 'index.jsp') {
$('#siteloader').load(page + '.jsp');
$('ul#menu li a').css({"color": "#000"});
$(this).css({"color": "#ca4b00"});
return false;
}
return true;
});
//set the color to the item in which the mouse is hovering ontop
// a bottom (border) line go to the item where i'm hover
$('ul#menu li a').hover(function() {
$('ul#menu li a').css({"color": "#000"});
$('ul#menu li a').css({"border-bottom-style": "none"});
$(this).css({"color": "#ca4b00"});
$(this).css({"border-bottom": "4px solid"});
});
});
The problem with this code is that if I don't click at an item , the color and the bottom line are not set to the correct item. What do I need to do in order to have the line and the color set to the right item?
Upvotes: 0
Views: 112
Reputation: 3106
You have 2 options:
define the hover
and click
as separate functions and trigger them manually.
$(document).ready(function() { //load the index page into a div container
//set a bottom (border) line under the item of navigation bar
$('#siteloader').load('empleados.jsp');
$('ul#menu li a.active').css({"borderbottom": "4px solid"});
var onClick = function() {
var page = $(this).attr('href');
if (page !== 'index.jsp') {
$('#siteloader').load(page + '.jsp');
$('ul#menu li a').css({"color": "#000"});
$(this).css({"color": "#ca4b00"});
return false;
}
return true;
};
var onHover = function() {
$('ul#menu li a').css({"color": "#000"});
$('ul#menu li a').css({"border-bottom-style": "none"});
$(this).css({"color": "#ca4b00"});
$(this).css({"border-bottom": "4px solid"});
};
//When the hyperlink is clicked
// set the right color to the item of the navigation bar
$('ul#menu li a').click(onClick);
//set the color to the item in which the mouse is hovering ontop
// a bottom (border) line go to the item where i'm hover
$('ul#menu li a').hover(onHover);
var desiredElement = $('ul#menu li a').eq(0); // the element you want to apply the styles too. Change the `0` value to select other elements.
onClick.call(desiredElement); //call the function with the desired element as `this`
onHover.call(desiredElement); //call the function with the desired element as `this`
});
Upvotes: 1