Home > Blockchain >  Can this popup feature be applied for many users?
Can this popup feature be applied for many users?

Time:05-30

I made a popup feature, which shows the phone number of a user. I was able to apply this feature to one instance. A single user.

Normally, each user has a unique phone number. Each user's number's already embedded, it's just to reveal the numbers, for multiple users.

But then, I thought, what if I have lots of users as they come, to the site? How do I dynamically apply the same popup feature without writing the same lines of code I wrote for the single user, over and over again?

Please, help me out.

This is the JavaScript I wrote...

  let tansform_scale_0 = document.querySelector('.transform_scale_0');
    let num_btn = document.querySelector('.num_btn');

    num_btn.addEventListener('click', ()=>{
        if (!tansform_scale_0.classList.contains('scale_to_1')) {
            tansform_scale_0.classList.add('scale_to_1');
        } else {
            tansform_scale_0.classList.remove('scale_to_1');
        }
    })

Please view the code here: https://codepen.io/matthewdon/pen/MWQEvJM

CodePudding user response:

You need to extend the logic you've applied to each of your cards. For example, the simplest way is to use querySelectorAll rather than the querySelector you currently have.

This is very similar in that it will return you a list of matching elements which you can then loop over and add your event listeners to in much the same way you are doing now.

However to make things a bit easier, you will be better off looping over each of the containing .card elements first. That way you can scope a second querySelector to the containing element and leave the rest of your logic largely intact.

You can shortcut the click handler itself though, by using classList.toggle rather than manually checking the class and then adding/removing it as required.

const cards = document.querySelectorAll('.card');
cards.forEach((card) => {
  // rest of your click handler logic
})

Here's a snippet that brings all that together. I've put it on codepen as the editor on here isn't really suited to such a large amount of html: https://codepen.io/29b6/pen/VwQQqrw?editors=1111

  • Related