add class to element when hover over a separate class

60
March 27, 2018, at 03:13 AM

I would like a hidden image to display when hovering over some text. I have a page here.

https://image-hover-1.superhi.com/

My js is:

$(document).ready(function() {     
$('.text').hover(function(){     
    $('.photo').addClass('visible');    
},     
function(){    
    $('.photo').removeClass('hide');     
});
});   

My CSS is:

.hide {display: none;}
.visible {display: block;}
Answer 1

You can shorten css and js sections. you don't need toggle any class, just toggle image itself

$(document).ready(function() {      
  $('.text').hover(function(){      
     $('.photo').toggle();     
    })      
});
.photo{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<p class="text">Hello there</p> 
<img src="https://picsum.photos/200/300" class="photo"/>

Just beware of toggle whole set of images which you assign the class="photo". For this case the statement is $(this).next().toggle();

Answer 2

Use toggleClass its the right tool for that kind of situation

$(document).ready(function() {      
  $('.text').hover(function(){      
     $('.photo').toggleClass('visible');     
    })      
});
.photo{display:none;} 
.visible {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<p class="text">Hello there</p> 
<img src="https://picsum.photos/200/300" class="photo"/>

Answer 3
$(".photo").hide();
$(".text").hover(function(){
      $(".photo").show();
},
function(){
     $(".photo").hide();
 });
READ ALSO
Loading time of a double link css file

Loading time of a double link css file

I have this client that wants me to make him only with HTML and CSS all in this 2 files three table designsTables that are different in content and in number of rows

99
Need help identifying a scrolling effect [on hold]

Need help identifying a scrolling effect [on hold]

I'm working on a new site and would love to implement some type of scrolling effect similar to the website artofflightmoviecom

77
adjust text size in order to fit in div

adjust text size in order to fit in div

I have several Div containing various text (headers, paragraphs,

57