0

I am trying to do something like below.

I have 5 buttons in my site.the desire is if user press any of the button, it makes an effect of scaling down.the issue is,i don't want want all of them scale down when i click one of the buttons, so i came with this approach, but its showing me an error.so how can achieve this effect?

items = document.querySelectorAll('.tags');
for (var iterator = 0; iterator < items.length; iterator++){
  items[iterator].onclick = function () {    
    items[iterator].style.transform = 'scale(0.9, 0.9)';            
  }
}    
<button class='tags'>button1</button>
<button class='tags'>button2</button>
<button class='tags'>button3</button>
<button class='tags'>button4</button>
<button class='tags'>button5</button>

1
  • just use this in your function? Commented Sep 6, 2020 at 14:54

3 Answers 3

4

Use this.style.transforminstead of this.style.transform

items = document.querySelectorAll('.tags');
for (var iterator = 0; iterator < items.length; iterator++){
  items[iterator].onclick = function (iterator) {    
    this.style.transform = 'scale(0.9, 0.9)';            
  }
}  
<button class='tags'>button1</button>
<button class='tags'>button2</button>
<button class='tags'>button3</button>
<button class='tags'>button4</button>
<button class='tags'>button5</button>

Sign up to request clarification or add additional context in comments.

Comments

1

You can also use this approach,

function animateInit(event){
  event.target.style.transform = 'scale(0.9, 0.9)'; 
}
<button class='tags' onclick="animateInit(event)">button1</button>
<button class='tags' onclick="animateInit(event)">button2</button>
<button class='tags' onclick="animateInit(event)">button3</button>
<button class='tags' onclick="animateInit(event)">button4</button>
<button class='tags' onclick="animateInit(event)">button5</button>

Comments

1

Unfortunately I can not see all your code. The problem must be in the iterator declared with var. I just changed the var for let and works fine for me.

items = document.querySelectorAll('.tags');
for (let iterator = 0; iterator < items.length; iterator++){
  items[iterator].onclick = function () {    
    items[iterator].style.transform = 'scale(0.9, 0.9)';            
  }
}    
<button class='tags'>button1</button>
<button class='tags'>button2</button>
<button class='tags'>button3</button>
<button class='tags'>button4</button>
<button class='tags'>button5</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.