mouseover event to control fadeto

109 views Asked by At

I'm trying to cause an image to fadeTo to a particular opacity but triggered when the mouseover (mouseenter, mouseleave) is on the parent div.

The code below shows two div elements (working fine) but for some reason it doesn't work when i change ".children("div")" to ".children("img")" given that I actually have an image in there of course.

Is there some syntax or naming convention I'm missing?

$(document).ready(function(){
  
  $(".title").mouseenter(function(){
  $(this).children("img").fadeTo("fast", 0.8);
  });
  $(".title").mouseleave(function(){
        $(this).children("img").fadeTo("fast", 1.0);


  });
  
});
.wrap {
 width: auto;
 margin-left: 2%;
 margin-right: 2%;
 padding-left: 2%;
 padding-right: 2%;
 float: none;
}
.title {
 border: 1px solid #C1C1C1;
    background: #000;
 cursor: pointer;
 transition-property: all;
 transition-duration: 0.2s;
 transition-timing-function: ease;
 transition-delay: 0;
 margin-bottom: 0px;
 position: relative;
 margin-top: 40px;
}
img {
    height: 100px;
    width: 100px;
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  </head>
<div class="fluid wrap" ontouchstart="">
            <div class="title">
            <img src="https://inkplant.com/images/code/red-box.jpg"/>
            </div>
            </div>

2

There are 2 answers

1
HelloWorld On BEST ANSWER

You don't mention where the image is, but I think you want:

$(document).ready(function(){
  $(".title").mouseenter(function(){
        $(this).find("img").fadeTo("fast", 0.8);
        });
  $(".title").mouseleave(function(){
        $(this).find("img").fadeTo("fast", 1.0);
  });
});

This is because

.children

only affects direct descendants of your target element.

.find

will find any element that is a child of the target node

1
Mohamed-Yousef On

you have a syntax error with </div> after your <img> its a wrong typo I think

if your img with class box use

$(this).find(".box")

instead of

$(this).children("div")

if your img not have any class just use

 $(this).find("img")