3

I want to add EventListener for .author_show class to change .author styles... this is my code

<div class="post>
    <div class="post-cont>
        // Some text
        <div class="author_show"></div>
        <div class="author_show"></div>
        // Some text
    </div>
</div>
<div class="authors">
    <div class="author"></div>
    <div class="author"></div>
</div>
<script type="text/javascript">
var author_show = document.getElementsByClassName("author_show");
var authors = document.getElementsByClassName("author");
for(var i=0;i<authors.length;i++)
{
    author_show[i].addEventListener("mouseover",function(){
        authors[i].style.display = "block"; // Problem
    })
}
</script>

Thanks...

2 Answers 2

1

Try to create a scope per iteration,

for(var i=0; i<authors.length; i++) {
   (function(i) {
      author_show[i].addEventListener("mouseover",function(){
        authors[i].style.display = "block"; // Problem
      }); 
    })(i);
}

In your code the addEventListener will not cause any problem. But the style setting block will rely on an i that belongs to a single scope. As for loop iterates that i will be incremented and the final value of i will be reflected inside of all the events. So you have to create a scope per iteration.

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

Comments

0

This is what you're going for :

var author_show = document.getElementsByClassName("author_show");
var authors = document.getElementsByClassName("author");

for(var i=0;i<authors.length;i++) {
    (function(i) {
        var author = author_show[i];
        var style = authors[i].style;
        author.addEventListener("mouseover", function(){
            style.display = "block"; // Problem
        });
        author.addEventListener("mouseout", function(){
            style.display = "none"; // Problem
        });
    })(i);
}
.author {
   display : none;
}
<div class="post">
    <div class="post-cont">
        // Some text
        <div class="author_show">Show A</div>
        <div class="author_show">Show B</div>
        // Some text
    </div>
</div>
<div class="authors">
    <div class="author">Author A</div>
    <div class="author">Author B</div>
</div>

(see also this Fiddle)

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.