ll55 ll55 - 3 months ago 19
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 () {
}, function () {
$("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
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/


You can use this:


to select the correct title - see demo below:

$("img.gthumb").hover(function() {
}, function() {
$("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>
<table align="center" border="1" style="overflow:hidden;max-height:177px;">
      <img class="gthumb" src="http://i.imgur.com/V9vL6kg.png" width="175">
      <div class="title">Grand Theft Auto IV
      <img class="gthumb" src="http://i.imgur.com/V9vL6kg.png" width="175">
      <div class="title">GTA IV
        <br/>to be added</div>