I am quite new to writing my own jquery functions and I find debugging it very difficult as the error messages aren’t too helpful when put into google.
I have a navigation menu for page anchors that when each one is clicked the screen scrolls to the anchor, the elements will change color depending on which one and the hover color will also change. Very simple really, I think.
The scrolling always works, the animate works occasionally and the hover works put usually I have to click the link twice. The return false only works on the first link you click.
This uses the scrollTo and animate-colors plugins.
Can anyone tell me what I’m doing wrong?
$(".scrolltoanchor").click(function() {
$('a').removeClass('selected');
$(this).addClass('selected');
$.scrollTo($($(this).attr("href")), {
duration: 750
});
switch ($(this).attr("id")) {
case 'personal':
$('.scrolltoanchor').animate({color: '#E4D8B8'});
$(".scrolltoanchor").hover(
function() {
$(this).css('color', 'blue');
},function(){
$(this).css('color', '#E4D8B8');
});
break;
case 'achievements':
$('.scrolltoanchor').animate({color: '#ffffff'});
$(".scrolltoanchor").hover(
function() {
$(this).css('color', 'red');
},function(){
$(this).css('color', '#ffffff');
});
break;
case 'skills':
$('.scrolltoanchor').animate({color: '#dddddd'});
$(".scrolltoanchor").hover(
function() {
$(this).css('color', 'orange');
},function(){
$(this).css('color', '#ffffff');
});
break;
}
return false;
});
Sorry to ask to be spoonfed, but I have followed what I believed to be the correct syntax from what I have learnt. Is there something I should know that is stopping this working as I expect?
EDIT: Sorry I forgot, I get this error on the (on average) every second click of a scrolltoanchor link
Uncaught TypeError: Cannot read property ‘0’ of undefined
I can’t spot a real pattern. Sometimes it seems to happen only on ones that havent been clicked before, sometimes not.
Thanks
You’re taking the wrong approach.
You should bind the hover handlers once, and decide the colors based on which one was clicked.
Simplest way would probably to store the color data in a lookup table where the keys are the IDs of the elements.
Then bind the handlers once, and use the
idof the one clicked to set thecurrentcolor set.