0

The goal is simple. When hover over mydiv (gray) the child div of inner should appear. I'm trying to write code for that but the best I can come up with is showing all inner divs. Only the child inner div should appear. Please help me with the code for this, I will appreciate it, thank you :)

https://jsfiddle.net/wyeqgfjz/#&togetherjs=6wNtokkegm

HTML:

<div class="mydiv">
  <div class="inner"></div>
</div>

<div class="mydiv">
  <div class="inner"></div>
</div>

CSS:

.mydiv {
  background: #ccc;
  padding: 40px;
  margin-bottom: 40px;
}

.inner {
  background: red;
  padding: 40px;
}

jQuery:

var inner = $('.mydiv .inner'),
  mydiv = $('.mydiv');
inner.hide();
mydiv.each(function() {
  $(this).on('hover', function() {
    $(this).find(inner).toggle();
  });
});

2 Answers 2

3

There is no hover event, the events you want are mouseenter and mouseleave instead.
However, jQuery has a hover() method that combines the events for you.

Note that you don't have to use a loop, jQuery iterates internally for you.

var inner = $('.mydiv .inner'),
    mydiv = $('.mydiv');
    
inner.hide();

mydiv.hover(function() {
  $(this).find(inner).toggle();
});
.mydiv {
  background: #ccc;
  padding: 40px;
  margin-bottom: 40px;
}

.inner {
  background: red;
  padding: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">
  <div class="inner"></div>
</div>

<div class="mydiv">
  <div class="inner"></div>
</div>

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

4 Comments

using the variable inner will actually work in this instance: example
@empiric - indeed it does, jQuery does some magic to filter the collection it seems.
I wasn't sure about that either because of the initial selector. It is probably good to keep that in mind in case one encounters weird side effects
It's in the documentation for find, I looked it up before editing the answer. It was added in 1.6, and it does filter the passed in collection so as to work the same as a string selector.
2

No need to use script for this at all. Can do it with css alone by using :hover pseudo selector

.mydiv {
  background: #ccc;
  padding: 40px;
  margin-bottom: 40px;
}

.inner {
  background: red;
  padding: 40px;
  display:none;
}

.mydiv:hover .inner {
  display:block
}
<div class="mydiv">
  <div class="inner"></div>
</div>

<div class="mydiv">
  <div class="inner"></div>
</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.