Typetecture
Typetecture

Reputation: 25

JQuery show/hide elements with matching title and alt tag

Is it possible to show an image via mouseover on a link whose only matching tags are title and alt?

My CMS can only generate matching title and alt tags for 2 completely seperated elements. It roughly looks like this:

<a href="#" title="aubergine">hover this to show image</a>

<img width="300" height="300" alt="aubergine" src="http://i.imgur.com/0MmkDiI.jpg"></img>

I've been able to target the img like so:

$('a').mouseover(function() {
$('[alt="aubergine"]').css( "opacity", "100" );
});

But instead of the specific target [alt="aubergine"] i would have to get the image via [alt="title of this link i just hovered"].

Here is a fiddle with the working prototype so far: https://jsfiddle.net/82xnqu6j/1/

Upvotes: 1

Views: 2111

Answers (3)

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

Use jQuery to pull out the title attribute of your current element, like in the following live example.

That way you can generalize it for all matching links.

Live Example:

$('a').mouseover(function() {
  $('[alt="' + $(this).attr("title") + '"]').css( "opacity", "1" );
});

$('a').mouseout(function() {
  $('[alt="' + $(this).attr("title") + '"]').css( "opacity", "0" );
});
img {opacity:0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" title="aubergine">hover this to show image</a>

<img width="100" height="100" alt="aubergine" src="http://i.imgur.com/0MmkDiI.jpg"></img>

JSFiddle Version: https://jsfiddle.net/82xnqu6j/4/

Upvotes: 2

iplus26
iplus26

Reputation: 2637

You can just use $(this).attr('title') to choose any attribution of the element in jQuery, same as this.title in native JavaScript.

$('a').mouseover(function() {
  $('[alt="' + $(this).attr('title') + '"]').css("opacity", "100");
});

$('a').mouseout(function() {
  $('[alt="' + $(this).attr('title') + '"]').css("opacity", "0");
});
img {
  opacity: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" title="aubergine">hover this to show image</a>
<a href="#" title="test">hover this to show image</a>
<img width="300" height="300" alt="aubergine" src="http://i.imgur.com/0MmkDiI.jpg"></img>
<img width="300" height="300" alt="test" src="https://i.sstatic.net/gVqLo.png"></img>

Upvotes: 0

jmd1921
jmd1921

Reputation: 46

Simply try getting the actual title from the link and using it as part of the selector

    $('a').mouseover(function() { 
        $('[alt="'+this.title+'"]').css( "opacity", "100" );
    });

This applies to any attribute, such as title, src, href, etc.

Check the w3schools page for this in: http://www.w3schools.com/cssref/sel_attribute_value.asp

Upvotes: 0

Related Questions