ll55 ll55 - 4 days ago 6
CSS Question

clone - using same javascript and css for multiple elements

First, I have an image and a title:

<!-- HTML code -->
<img class="gthumb" src="http://i.imgur.com/V9vL6kg.png" width="175"><div class="title">Grand Theft Auto IV<br/>俠盜獵車手IV</div>


Second, I hide the title by default:

// CSS code
.title { display: none; position: absolute; }


Third, I use jQuery to show the title when hovering the image:

// JS code
$("img.gthumb").hover (function () {
$("div.title").show();
}, function () {
$("div.title").hide();
});
$("img.gthumb").mousemove(function(e) {
var width = $('div.title').width();
var height = $('div.title').height();
$("div.title").css("top",e.pageY - height - 5);
$("div.title").css("left",e.pageX - width / 2);
});


And then I clone the
HTML code
to display another group of image and title, the original title and the cloned title are overlapping each other.

I cannot use
this
or
$(this)
as
$("img.gthumb")
acts as something like event listeners.

Cloning and changing the class names one by one is not a good solution, how can I use the same javascript and css for multiple elements (in this case is images and titles)? Thanks a lot.

jsfiddle: http://jsfiddle.net/ap94pt9q/1/

Answer

You can use this:

$(this).next("div.title")

to select the correct title - see demo below:

$("img.gthumb").hover(function() {
  $(this).next("div.title").show();
}, function() {
  $(this).next("div.title").hide();
});
$("img.gthumb").mousemove(function(e) {
  var width = $(this).next('div.title').width();
  var height = $(this).next('div.title').height();
  $(this).next("div.title").css("top", e.pageY - height - 5);
  $(this).next("div.title").css("left", e.pageX - width / 2);
});
.title {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  width: auto;
  height: auto;
  display: none;
  color: white;
  font-size: large;
  text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/>
<br/>
<br/>
<table align="center" border="1" style="overflow:hidden;max-height:177px;">
  <tr>
    <td>
      <img class="gthumb" src="http://i.imgur.com/V9vL6kg.png" width="175">
      <div class="title">Grand Theft Auto IV
        <br/>俠盜獵車手IV</div>
    </td>
    <td>
      <img class="gthumb" src="http://i.imgur.com/V9vL6kg.png" width="175">
      <div class="title">GTA IV
        <br/>to be added</div>
    </td>
  </tr>
</table>

Comments