2

I have the following code, which fetches and assigns .on() events to certain elements added to a nav. The problem is that if I then run this function again, it will assign .on twice and thus when I click one of these elements it will run twice when I want it to only run one time.

How can I remove (OR RESET) the .on() event? Or prevent it from running twice in one click?

function fetchPlaylists() {
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      $('.playlistsList').html('');
      $('.playlistsListOptions').html('');

      firebase
     .database()
     .ref('users/'+user.uid+'/Playlists')
     .orderByChild('timestamp')
     .once('value')
     .then(snapshot => {
       snapshot.forEach((item) => {
         // console.log(item.key);
         var playlistName = item.key;
         var playlistID = item.child("playlistID").val();
         // console.log(playlistID, " ID");

         //Add to the nav for playlists, and also append to the arr of playlists
         // console.log(playlistID);
         $('.playlistsList').append('<li class="playlistDiv" id="'+playlistID+'"><label class="playlistItem" id="playlistItem">'+playlistName+'</label></li>');
         $('.playlistsListOptions').append('<li class="playlistOptionDiv" id="'+playlistID+'"><label class="playlistOptionItem" id="playlistOptionItem">'+playlistName+'</label></li>');
       })

       // $(".playlistsList").on("click", ".playlistDiv", function(e) {
       //    // var int = parseInt($(this).attr('id'), 10);
       //    console.log("Somthing again again");
       //    $(".playlistDiv").children('.playlistItem').css("color","#919191");
       //    var playlistID = $(this).attr('id');
       //    $(this).children('.playlistItem').css("color","white");//#919191
       //    fetchAndDisplayPlaylist(playlistID, user.uid);
       // });
       //
       // $(".playlistsListOptions").on("click", ".playlistOptionDiv", function(e) {
       //    // var int = parseInt($(this).attr('id'), 10);
       //    $(".playlistOptionDiv").children('.playlistOptionItem').css("color","#919191");
       //    var playlistID = $(this).attr('id');
       //    $(this).children('.playlistOptionItem').css("color","white");//#919191
       //    addToXPlaylist(playlistID, currentPortal);
       // });
       //
       // $(".playlistOptionDiv").hover(
       //   // console.log("Somddjfgbskhfgbfhjd", $(this).children('.playlistOptionDiv').attr('id'));
       //   function() {
       //     var playlistID = $(this).attr('id');
       //     // console.log(playlistID);
       //     $(this).children('.playlistOptionItem').css("color","white");
       //     // $(this).children('.playlistOptionItem').css("background-color","rgba(255, 255, 255, 0.2)");
       //   }, function() {
       //     var playlistID = $(this).attr('id');
       //     $(this).children('.playlistOptionItem').css("color","#919191");
       //     // $(this).children('.playlistOptionItem').css("background-color","transparent");
       //   }
       // );

     })
     .catch(error => {
       //There was an error fetching playlists
       alert(error)
     });
     $(".playlistsList").on("click", ".playlistDiv", function(e) {
        // var int = parseInt($(this).attr('id'), 10);
        console.log("Somthing again again");
        $(".playlistDiv").children('.playlistItem').css("color","#919191");
        var playlistID = $(this).attr('id');
        $(this).children('.playlistItem').css("color","white");//#919191
        fetchAndDisplayPlaylist(playlistID, user.uid);
     });

     $(".playlistsListOptions").on("click", ".playlistOptionDiv", function(e) {
        // var int = parseInt($(this).attr('id'), 10);
        $(".playlistOptionDiv").children('.playlistOptionItem').css("color","#919191");
        var playlistID = $(this).attr('id');
        $(this).children('.playlistOptionItem').css("color","white");//#919191
        addToXPlaylist(playlistID, currentPortal);
     });


   } else {
     //User not signed up.
   }
  });
}
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • have you tried using onclick() than using .on(...)? – Manjuboyz Feb 26 '20 at 04:47
  • 2
    How to remove `on`? Using `off`. But you'd be better off rethinking your approach, in one of several ways: using more specific live handlers (e.g. `$("body.hasSong').on('hover', '.playlistOptionDiv', ...)` and then just toggling a class to switch the live always-on handler, using a conditional inside the always-on handler, etc... Adding and removing handlers is a hassle. – Amadan Feb 26 '20 at 04:48
  • https://api.jquery.com/one/ is also for the purpose. – techie_28 Feb 26 '20 at 05:05
  • Does this answer your question? [Provide onclick dynamically and avoid duplicate event calling](https://stackoverflow.com/questions/60386947/provide-onclick-dynamically-and-avoid-duplicate-event-calling) – Nguyễn Văn Phong Feb 26 '20 at 05:50

3 Answers3

4

You can use something like this:

Unbind() :

Remove a previously-attached event handler from the elements. [jQuery website].

 $(".playlistsList").unbind("click").on("click",".playlistDiv", function(event){...}
Manjuboyz
  • 6,978
  • 3
  • 21
  • 43
  • Perfect this did it! –  Feb 26 '20 at 04:52
  • Need to wait 5 min unfortunately. Will be back! –  Feb 26 '20 at 04:53
  • 3
    The `unbind()` method was deprecated in version 3.0. Use the `off()` method instead. – hoangkianh Feb 26 '20 at 04:57
  • Like @hoangkianh said, use .`off()` the same way you use .`on()` to attach. Eg: `$(".playlistsList")..off("click",".playlistDiv"),on("click",".playlistDiv", function(event){...}`) – Tommy Feb 26 '20 at 04:59
0

first you need to empty your div and fetch data again. i just add one code ($("#.playlistDiv").empty())

function fetchPlaylists() {
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      $('.playlistsList').html('');
      $('.playlistsListOptions').html('');

      firebase
     .database()
     .ref('users/'+user.uid+'/Playlists')
     .orderByChild('timestamp')
     .once('value')
     .then(snapshot => {
       snapshot.forEach((item) => {
         // console.log(item.key);
         var playlistName = item.key;
         var playlistID = item.child("playlistID").val();
         // console.log(playlistID, " ID");

         //Add to the nav for playlists, and also append to the arr of playlists
         // console.log(playlistID);
         $('.playlistsList').append('<li class="playlistDiv" id="'+playlistID+'"><label class="playlistItem" id="playlistItem">'+playlistName+'</label></li>');
         $('.playlistsListOptions').append('<li class="playlistOptionDiv" id="'+playlistID+'"><label class="playlistOptionItem" id="playlistOptionItem">'+playlistName+'</label></li>');
       })

       // $(".playlistsList").on("click", ".playlistDiv", function(e) {
$("#.playlistDiv").empty()
       //    // var int = parseInt($(this).attr('id'), 10);
       //    console.log("Somthing again again");
       //    $(".playlistDiv").children('.playlistItem').css("color","#919191");
       //    var playlistID = $(this).attr('id');
       //    $(this).children('.playlistItem').css("color","white");//#919191
       //    fetchAndDisplayPlaylist(playlistID, user.uid);
       // });
       //
       // $(".playlistsListOptions").on("click", ".playlistOptionDiv", function(e) {
       //    // var int = parseInt($(this).attr('id'), 10);
       //    $(".playlistOptionDiv").children('.playlistOptionItem').css("color","#919191");
       //    var playlistID = $(this).attr('id');
       //    $(this).children('.playlistOptionItem').css("color","white");//#919191
       //    addToXPlaylist(playlistID, currentPortal);
       // });
       //
       // $(".playlistOptionDiv").hover(
       //   // console.log("Somddjfgbskhfgbfhjd", $(this).children('.playlistOptionDiv').attr('id'));
       //   function() {
       //     var playlistID = $(this).attr('id');
       //     // console.log(playlistID);
       //     $(this).children('.playlistOptionItem').css("color","white");
       //     // $(this).children('.playlistOptionItem').css("background-color","rgba(255, 255, 255, 0.2)");
       //   }, function() {
       //     var playlistID = $(this).attr('id');
       //     $(this).children('.playlistOptionItem').css("color","#919191");
       //     // $(this).children('.playlistOptionItem').css("background-color","transparent");
       //   }
       // );

     })
     .catch(error => {
       //There was an error fetching playlists
       alert(error)
     });
     $(".playlistsList").on("click", ".playlistDiv", function(e) {
        // var int = parseInt($(this).attr('id'), 10);
        console.log("Somthing again again");
        $(".playlistDiv").children('.playlistItem').css("color","#919191");
        var playlistID = $(this).attr('id');
        $(this).children('.playlistItem').css("color","white");//#919191
        fetchAndDisplayPlaylist(playlistID, user.uid);
     });

     $(".playlistsListOptions").on("click", ".playlistOptionDiv", function(e) {
        // var int = parseInt($(this).attr('id'), 10);
        $(".playlistOptionDiv").children('.playlistOptionItem').css("color","#919191");
        var playlistID = $(this).attr('id');
        $(this).children('.playlistOptionItem').css("color","white");//#919191
        addToXPlaylist(playlistID, currentPortal);
     });

     $(".playlistOptionDiv").hover(
       // console.log("Somddjfgbskhfgbfhjd", $(this).children('.playlistOptionDiv').attr('id'));
       function() {
         var playlistID = $(this).attr('id');
         // console.log(playlistID);
         $(this).children('.playlistOptionItem').css("color","white");
         // $(this).children('.playlistOptionItem').css("background-color","rgba(255, 255, 255, 0.2)");
       }, function() {
         var playlistID = $(this).attr('id');
         $(this).children('.playlistOptionItem').css("color","#919191");
         // $(this).children('.playlistOptionItem').css("background-color","transparent");
       }
     );

   } else {
     //User not signed up.
   }
  });
}
Sagar Kumar
  • 55
  • 1
  • 5
0

You should use .off()

 $(".playlistsList").off("click").on("click",".playlistDiv", function(event){...}

However

As .playlistsList is static, you should move the listener event outside the fetchPlaylists method.

Format: $(staticAncestors).on(eventName, dynamicChild, function() {});

So in your case

// set events
$(".playlistsList").on("click",".playlistDiv", function(event)

Read the following answer to have a better understanding.

https://stackoverflow.com/a/60387074/9071943

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56