LampPost LampPost - 7 months ago 11
Javascript Question

jQuery Animate works after first click

I'm trying to hook up jQuery's animate ability with a bookmark id on a site. When I click on the link, it went to my bookmark id without animation but when I clicked the same link again, the animation works.

var TitleNav = React.createClass({
handleSubmitClick:function()
{
$('a').click(function()
{
$('html, body').animate(
{
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
},

render: function() {
return(
<div>
<ul className = "nav">
<li className = "navworkspace" onClick ={this.handleSubmitClick}><a href="#work">Work</a></li>
</ul>
</div>
);
}
});


I assume it is the way that the components are called since components do not wait on each other. Is there a way to fix this?

Note: I am using React.Js to render my site.

Answer

The reason is your handleSubmitClick function is only binding the click event handler to the link, but not trigger the event. So the first time you click on the link, it does nothing but only bind the event. After that, since the handler is binded, the animation works the 2nd times and so on. you can change the code to

var TitleNav = React.createClass({
    componentDidMount:function()
    {
        $('a').click(function()
        {
            $('html, body').animate(
            {
                scrollTop: $( $.attr(this, 'href') ).offset().top
            }, 500);
            return false;
        });
    },

    render:  function() {
        return(
            <div>
                <ul className = "nav">
                    <li className = "navworkspace"><a href="#work">Work</a></li>
                </ul>
            </div>
        );
    }
});

or you can do this

var TitleNav = React.createClass({
    handleSubmitClick:function()
    {

            $('html, body').animate(
            {
                scrollTop: $( $.attr(this, 'href') ).offset().top
            }, 500);
            return false;

    },

    render:  function() {
        return(
            <div>
                <ul className = "nav">
                    <li className = "navworkspace" ><a href="#work" onClick ={this.handleSubmitClick}>Work</a></li>
                </ul>
            </div>
        );
    }
});
Comments