Skip to content Skip to sidebar Skip to footer

Trigger Click Event Only Once

I want to trigger the click event only when the screen width of the browser is 800px, however with the logic below, the click event is triggered back and forth nonstop when i reach

Solution 1:

One possible way could be to remove the resize listener when no longer needed using EventTarget.removeEventListener() like this:

functionresizeListener() {
  if (window.innerWidth === 800) {
    window.removeEventListener('resize', resizeListener);
    $('a[data-click="sidebar-minify"]').trigger('click');
    console.log('click event triggered');
  }
}

window.addEventListener('resize', resizeListener);

Solution 2:

window.onresize = function()
{
 const width = window.innerWidth;
 if(width === 800)
 {
   // give anker link class then remove that after condition true


    $('.anker').trigger('click');


    console.log('click event triggered');

   $('a[data-click="sidebar-minify"]').removeClass("anker");
 }
}

Solution 3:

Like @Pete said in the comments, you have different options.

You could use a boolean to track if the event already was fired:

var isResized = false;
window.onresize = function()
{
     const width = window.innerWidth;
     if(width === 800 && !isResized)
     {
        isResized = true;
        alert("test");
     }
}

You also can use the one function for the click of the a tag, which unbinds the click after the first use:

window.onresize = function()
{
     const width = window.innerWidth;
     if(width === 800)
     {
        $('a[data-click="sidebar-minify"]').trigger('click');
        console.log('click event triggered');
     }
}

$('a[data-click="sidebar-minify"]').one("click", function(){
    alert("test");
});

Post a Comment for "Trigger Click Event Only Once"