3

I'm trying to trigger 'for loop' by clicking, with 'addEventListener' function. I've seen lots of questions asking how to make addEventListener embedded in for loop, but couldn't find a case of the opposite, for loop embedded in addEventListener.

This is the html -----html-----

<div id="myDiv">
  <p id="myP">HO HO HO</p>
</div>

-----JavaScript-----

    var myDiv = document.getElementById("myDiv");

    var objs = {Aman : function(){myDiv.style.background="yellow"}, 
                Bman : function(){myDiv.style.margin = "30px"},
                Cman : function(){myDiv.style.border ="blue"}};

    function loop(){
      for(var i=0; i < objs.length ; i++){
          return objs[Object.keys(objs)[i]] }
                   };

    myDiv.addEventListener("click", loop);

I really can't find why this doesn't work. Really appreciate for you genius.

p.s; If this can't work, then how can I link more than one events to just one 'addEventListener' phrase?

1
  • The condition for(var i=0; i < objs.length ; i++){ is incorrect. You can get the Object length using Object.keys.length. Commented Mar 21, 2020 at 13:28

2 Answers 2

2

Your code has two problems. 1. At for loop you use objs.length but there is no length of an object. 2. Into the objs you define functions. But you don't call the functions.

You can check this out. It may help you.

var myDiv = document.getElementById("myDiv");

var objs = {
  Aman: function() {
    myDiv.style.background = "yellow";
  },
  Bman: function() {
    myDiv.style.margin = "30px";
  },
  Cman: function() {
    myDiv.style.border = "blue";
  }
};

function loop() {
  // loop through Object.keys(objs).length not objs.length
  for (let i = 0; i < Object.keys(objs).length; i++) {
    objs[Object.keys(objs)[i]](); // You have to call the function
  }
}

myDiv.addEventListener("click", loop);
<div id="myDiv">
  <p id="myP">HO HO HO</p>
</div>

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

Comments

2

You have to loop through properties of your object.

    var myDiv = document.getElementById("myDiv");

    var objs = {
      Aman: function() {
        myDiv.style.background = "yellow";
      },
      Bman: function() {
        myDiv.style.margin = "30px";
      },
      Cman: function() {
        myDiv.style.border = "blue";
      }
    };
    function loop() {
      for (var key of Object.keys(objs)) {
        objs[key]();
      }
    }

    myDiv.addEventListener("click", loop);
    <div id="myDiv">
      <p id="myP">HO HO HO</p>
    </div>

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.