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

烂漫一生 提交于 2021-02-08 09:51:05

问题


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.


回答1:


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();
});




来源:https://stackoverflow.com/questions/55659793/how-to-call-a-function-from-click-event-inside-another-click-event-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!