MagicRecon MagicRecon - 5 months ago 9
jQuery Question

Javascript - How to turn this into a simple function

$(document).ready(function()
{
// $('.pull-me').click(function()
// {
// $('.login').slideToggle('slow')
// });

$('#thumbnail1').mouseenter(function()
{
$('#thumbnailTitle1').css('visibility', 'visible')
});
$('#thumbnail1').mouseleave(function()
{
$('#thumbnailTitle1').css('visibility', 'hidden')
})


$('#thumbnail2').mouseenter(function()
{
$('#thumbnailTitle2').css('visibility', 'visible')
});
$('#thumbnail2').mouseleave(function()
{
$('#thumbnailTitle2').css('visibility', 'hidden')
})


$('#thumbnail3').mouseenter(function()
{
$('#thumbnailTitle3').css('visibility', 'visible')
});
$('#thumbnail3').mouseleave(function()
{
$('#thumbnailTitle3').css('visibility', 'hidden')
})
});


I'm very new to Javascript but am trying to learn. I aware this is jQuery but would like to know if there is a quicker way to do this code, like create a smaller function that i can call up to display/hide the text.

Because i will be adding more thumbnails and i don't want to have to write it all out for every photo and text that i display on the photo.

Answer

The following is an option.

( function( $, window, undefined ) {

  var handle_mouse_events = function handle_mouse_events( thumbnail_selector, thumbnail_title_selector ) {
    
    $( thumbnail_selector ).mouseenter(
      function() {
        $( thumbnail_title_selector ).css( 'visibility', 'visible' );
      }
    );
    
    $( thumbnail_selector ).mouseleave(
      function() {
        $( thumbnail_title_selector ).css( 'visibility', 'hidden' );
      }
    );
    
  };
  
  handle_mouse_events( '#thumbnail1', '#thumbnailTitle1' );
  handle_mouse_events( '#thumbnail2', '#thumbnailTitle2' );
  handle_mouse_events( '#thumbnail3', '#thumbnailTitle3' );

} )( jQuery, this );
.image_container > div {
  display : inline-block;
  width : 150px;
  height : 200px;
}

span {
  visibility : hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image_container">
  <div id="thumbnail1">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=150%C3%97150&w=150&h=150" />
    <span id="thumbnailTitle1">Title #1</span>
  </div>
  <div id="thumbnail2">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=150%C3%97150&w=150&h=150" />
    <span id="thumbnailTitle2">Title #2</span>
  </div>
  <div id="thumbnail3">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=150%C3%97150&w=150&h=150" />
    <span id="thumbnailTitle3">Title #3</span>
  </div>
</div>