Lisandro
Lisandro

Reputation: 115

How to call a function from click event inside another click event function?

I have 2 functions that triggers when an element is clicked. However, i want to use the first function that should be executed in another function via click event. I am still a newbie.

I already tried calling the function and declaring the function name inside the other function where i want it to be executed. Is it not working because the first function can only be triggered vie click event on its element? I also nested the click event on a function but it didn't work as well.

$(document).ready(function()
function toggleMenuClick(){

$('.menu-link').click(function (normal){
    normal.preventDefault();
    $('.menu-link').toggleClass('close');
    $('.overlay-menu').toggleClass('active');
    $('.menu-link').toggleClass('fixed');
    $('nav ul').toggleClass('show');
    $('nav ul li').toggleClass('fade-in');
    $('body').toggleClass('min-height');

    if ($(window).scrollTop() <= 99){
        $('.menu-link').toggleClass('white');
    }
});

}

toggleMenuClick();

$('.scroll-link').click(function(navigate){
   navigate.preventDefault();
      $("html, body").animate({
      scrollTop: $(this.hash).offset().top
      }, 700);
toggleMenuClick();
});
});

I want all the classes from toggleMenuClick to be toggled when .scroll-link is clicked as well.

Upvotes: 0

Views: 2772

Answers (1)

frodo2975
frodo2975

Reputation: 11725

You need to make toggleMenuClick a separate function, outside your click handlers, so that you can call it independently.

It would look something like this:

var toggleMenuClick = function() {
    // Do classes stuff...
}


$('.menu-link').click(function(e) {
    e.preventDefault();
    toggleMenuClick();
});

$('.scroll-link').click(function(e){
    // Do stuff...

    // Now you can call your function
    toggleMenuClick();
});


Upvotes: 2

Related Questions