Shaun Loftin Shaun Loftin - 5 months ago 18
Javascript Question

jQuery not triggering event in hover state

I'm currently trying to make a navigational menu that on click scrolls to a div positioned lower on the page. Initially it worked but as I added a CSS transition to highlight the text, the jQuery will no longer trigger the scrolling to happen upon clicking it.

$("#about, #about:hover").click(function() {
$('html,body').animate({
scrollTop: $("#box1").offset().top},
'slow');
});


The
#about
id is a part of the nav menu and will scroll to
#box1
on click. I've tried adding the hover state to the selector, changing it to
.trigger
rather than
.click
but I'm not seeing a simple solution. I've recreated the event in Chrome, Safari, and using JSFiddle.

Is the JQuery conflicting with the transition, the hover state, or my code in general?

EDIT: It is working in the Fiddle example but the event still isn't happening when produced locally (everything is linked and correct with no errors in console).

Answer

Your JS code runs before the DOM is fully loaded.

Put the JS inside document.ready();:

$(document).ready(function () {
    $("#about, #about:hover").click(function () {
        $('html,body').animate({
            scrollTop: $("#box1").offset().top
        },
            'slow');
    });

    $("#portfolio, #portfolio:hover").click(function () {
        $('html,body').animate({
            scrollTop: $("#box2").offset().top
        },
            'slow');
    });

    $("#social, #social:hover").click(function () {
        $('html,body').animate({
            scrollTop: $("#box3").offset().top
        },
            'slow');
    });

    $("#contact, #contact:hover").click(function () {
        $('html,body').animate({
            scrollTop: $("#box4").offset().top
        },
            'slow');
    });
});

See updated JSFiddle

Comments