Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 74325

How to keep track of items in a list and detect which item it is when its clicked?

$
0
0

I have a search bar which when the user presses a button appends to the ul users whose names closely match. I now need to detect a click on a item and know which item it is so I can fetch additional content.

I have attempted to make this work in a variety of ways, one of which is shown bellow

JS: i added only the relevent code which runs inside a function called to fetch.

var searchUsersArr=[];//Made up of User() objects added as they are returned//global scope
 ...
if (c.exists()) {
    // document.getElementById('searchResultsList').style.display = 'block';
    document.getElementById('searchNav').style.display = 'block';
    var number = 0;
    //user1 will be inidex 0 so it tracks the array perfectly
    c.forEach((item, i) => {
      // console.log(item.child('username').val());
      var username = item.child('username').val();
      var uid = item.child('UID').val();
      var userObj = new User();
      userObj.username = username;
      userObj.uid = uid;
      userObj.num = number;
      searchUsersArr.push(userObj);
      number++;

      firebase
     .database()
     .ref('users/'+uid)
     .once('value')
     .then(snap => {
       var profileImg = snap.child('profile_picture').val();
       userObj.profileImage = profileImg;
       // searchUsersArr.push(userObj);
       //display user (Add)
       $('.searchResultsList').append('<li class="searchUserDiv" id="'+userObj.num+'"><img class="searchUserProfImg" id="searchUserProfImg" src="'+profileImg+'"><label class="searchUsername" id="searchUsername">'+username+'</label></li>');
       // number++;
       console.log(userObj.num, "", username);
       if (newHeight<400) {
         newHeight = document.getElementById("searchResultsList").offsetHeight+30;//document.getElementById(newHeight).offsetHeight+newHeight;//document.getElementsByClassName("searchUserDiv").offsetHeight
         document.getElementById('searchNav').style.height = ''+newHeight+'px';
       }
     })
    });

    $(".searchResultsList").on("click", function() {
      var int = parseInt($(this).find('li').attr('id'), 10);
      console.log(int, "user pressed on ", searchUsersArr[int].uid, searchUsersArr[int].username, searchUsersArr[int].pofileImage);
      var user1 = searchUsersArr[int];
      // console.log(user1);
      showUsersProfile(user1.uid, user1.username, user1.pofileImage);
    });

  }

How can I know which item was clicked and use the data associated with it in the searchUsersArr?


Viewing all articles
Browse latest Browse all 74325

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>