0

At the moment I have a javascript function which looks for an id and changes some CSS. However I want this function to run on multiple divs. Therefore I need my function to look for a class or a data attribute. Please can you help me!

<script>
  var div = document.getElementById('hover')
  div.onclick = function () {
    this.style.width = '800px'
    this.style.transition = 'all 1s'
    this.style.backgroundColor = 'red'
  }
</script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Matt Hammond
  • 372
  • 2
  • 11

2 Answers2

1

You need to use a class, which is better. And loop it through!

<script>
  var divs = document.getElementsByClassName('hover');
  for (var i = 0; i < divs.length; i++)
    divs[i].onclick = function () {
      this.style.width = '800px'
      this.style.transition = 'all 1s'
      this.style.backgroundColor = 'red'
    }
</script>

Example using addEventListener:

<script>
  var divs = document.getElementsByClassName('hover');
  for (var i = 0; i < divs.length; i++)
    divs[i].addEventListener("click", function () {
      this.style.width = '800px'
      this.style.transition = 'all 1s'
      this.style.backgroundColor = 'red'
    }, false);
</script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

You could wrap all your elements inside a common parent, then you apply your click event handler to that parent, checking the target that originated the event.

Doing so you need to attach the event just to a single element (and not to every single element).

Also, your style should be declared in the CSS as a class, so you only need to switch that specific class (and it's always better to keep off css from javascript, for the mantainability)

here is a simple example http://codepen.io/anon/pen/jPwXVr

CSS

.open {
  width: 800px;
  -webkit-transition  : all 1s;
  -moz-transition  : all 1s;
  transition  : all 1s;
  background: red;
}

JS

 document.getElementById('wrap').addEventListener('click', function(ev) {
  var target = ev.target
  if (target.nodeName === 'DIV') {
      target.className = 'open';        
  } 
}, false);

if the structure of your markup makes impossibile to use a common wrapper you could attach the event on the body element, like so

http://codepen.io/anon/pen/aOwPWY?editors=011

CSS

.element {
  width: 800px; 
  -webkit-transition  : all 1s;
  -moz-transition  : all 1s;
  transition  : all 1s;
}

.element.open {
  background: red;
}

JS

document.body.addEventListener('click', function(ev) {
   var t = ev.target;

   /* I used classList for the sake of brevity, check caniuse.com
      for its support across browser */

   if (t.classList.contains('element')) {
       t.classList.toggle('open');        
   } 
}, false);
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177