jQuery hover on imagemap does not work - javascript
I have an imagemap and want to add a jQuery hover. Basically the whole image shall be replaced with a new one, based on an imagemap. Hovering on certain parts of the image shall result in replacing the image completely. On a mouseout of the mapped areas, it shall flip back to the imagemap. It works fine doing the imageflip with javascript, but I want to change it to jQuery in order to have mor control about the fadeIn and stuff like this. It just seems easier in jQuery.
Here is what Ive got.
<html>
<head>
<!-- LINK ZU JQUERY ONLINE-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
//PRELOAD THE IMAGES
original = new Image(698, 360);
original.src = "imagenes_png/bosque_mapa.png";
azul = new Image(698, 360)
azul.src = "imagenes_png/azul_mouse.png";
verde = new Image(698, 360)
verde.src = "imagenes_png/verde_mouse.png";
//jQUERY HOVER
$(document).ready(function(){
$("#verdeA").hover(function() {
$(this).attr("src" , "verde.src");
}, function() {
$(this).attr("src" , "original.src");
$("#azulA").hover(function() {
$(this).attr("src" , "azul.src");
}, function() {
$(this).attr("src" , "original.src");
});
});
});
</script>
<body>
<!-- INSERT THE PICTURE -->
<img name="bosque" id="bosque" src="imagenes_png/bosque_mapa.png" width="698" height="360" border="0" usemap="#bosque_m" alt="Bosque con animales" />
<map name="bosque_m" id="bosque_m">
<area id="verdeA" shape="poly" coords="643,324,646,322,648,321,651,320,654,320,656,321,658,323,659,324,660,327,659,330,657,332,655,334,654,335,654,332,653,329,653,327,650,326,648,328,648,331,649,332,650,334,652,335,654,337,656,338,658,339,660,341,662,342,662,345,661,348,660,350,657,351,656,351,656,346,656,345,653,347,651,350,650,351,651,353,651,354,653,356,656,356,658,356,660,356,662,356,666,354,668,351,669,349,670,347,669,346,665,346,666,342,667,341,668,340,670,339,672,339,674,341,676,344,676,347,675,351,672,355,670,357,669,360,642,360,644,356,646,353,647,350,648,346,650,340,650,337,646,332,645,330,644,327,643,324"
alt="" />
<area id="azulA" shape="poly" coords="472,249,476,249,479,250,483,251,484,255,485,258,487,261,489,263,493,265,498,266,501,268,504,270,504,271,499,270,495,269,489,268,486,269,484,270,480,269,476,268,473,266,470,262,469,260,468,256,470,253,472,249"
alt="" />
</map>
</body>
</html>
First I preload the images that the imageflip works without delay. Then I delcare the jQuery function, based on the id in my imagemap and then I add the names of the pictures assigned in the preloading.
Buut, it does not work, at all. Nothing is happening.
Where is the mistake?
There are two problems:
First, when you refer to $(this) in your hover handlers, $(this) is referring to your <area> elements, not your <img>. You'll want to refer instead to $("#bosque").
Second, you are setting the src attribute to the actual strings verde.src, azul.src and original.src. It's as if you were saying <img src="verde.src">, which is not what you want. Remove the quotes from around those strings, as in: $("#bosque").attr("src", verde.src"); so that you are setting src equal to the src property of the verde object and not just to a relative URL that is broken.
So the hover section becomes this:
$(document).ready(function(){
$("#verdeA").hover(function() {
$("#bosque").attr("src" , verde.src);
}, function() {
$("#bosque").attr("src" , original.src);
$("#azulA").hover(function() {
$("#bosque").attr("src" , azul.src);
}, function() {
$("#bosque").attr("src" , original.src);
});
});
});
Which only reacts to the mapped areas:
Related
New IMG title disappears when changing via javascript
I have an image that changes its src onclick. This functionality works fine, but I need to change the img title attribute as well. My code changes the title but only keeps the change while hovering my mouse over the img. When I onmouseout of the img, FF Developer shows the title reverting to empty, ultimately not saving the new img title. Thought it was a browser issue but other browsers do the same. Ideas? <script type="text/javascript"> function my_func() { if (document.getElementById("changeable").src == "mysrc") { document.getElementById("changeable").src = "newsrc"; document.getElementById("changeable").setAttribute("title","Now showing newimg"); } else { document.getElementById("changeable").src = "newimg"; document.getElementById("changeable").setAttribute("title","Now showing defaultimg"); } } </script> <img id="changeable" onclick="my_func();" src="mysrc" title="Click to toggle" />
You checked condition wrong, Here, document.getElementById("changeable").src result should be "file:///home/system/Desktop/mysrc" use like, <html><script type="text/javascript"> function my_func() { if (document.getElementById("changeable").getAttribute('src') == "mysrc") { document.getElementById("changeable").setAttribute('src',"newsrc"); document.getElementById("changeable").setAttribute("title","Now showing newimg"); } else { document.getElementById("changeable").src = "newimg"; document.getElementById("changeable").setAttribute("title","Now showing defaultimg"); } } </script> <img id="changeable" onclick="my_func();" src="mysrc" title="Click to toggle" /> </html>
JavaScript event handler click thumbnail to enlarge image
So I am very new to Web Design and am having issues getting my click event handler to work.I cant change the html or css files. My task is to set a click handler to my thumbnails to enlarge the image in the img within the <figure> element. While also setting the figcaption text in the figure to the thumbs title attribute. I need to attach to the div id = thumbnails. My script is not enlarging my thumbnails or titles. This is my created HTML Doc: <!DOCTYPE html> <html lang="en"> <head > <meta charset="utf-8"> <title>Chapter 9 - Share Your Travels</title> <link rel="stylesheet" href="css/styles.css" /> <script type="text/javascript" src="js/chapter09-project02.js"> </script> ` `</head> <body> <header> <h2>Share Your Travels</h2> <nav><img src="images/menu.png"></nav> </header> <main> <figure id="featured"> <img src="images/medium/5855774224.jpg" title="Battle" /> <figcaption>Battle</figcaption> </figure> <div id="thumbnails"> <img src="images/small/5855774224.jpg" title="Battle"/> <img src="images/small/5856697109.jpg" title="Luneburg"/> <img src="images/small/6119130918.jpg" title="Bermuda" /> <img src="images/small/8711645510.jpg" title="Athens" /> <img src="images/small/9504449928.jpg" title="Florence" /> </div> </main> </body> </html> Js script: var thumbs = document.getElementById("thumbnails"); thumbs.addEventListener("click", function (e) { if (e.target.nodeName.toLowerCase() == 'img') { var clickedImageSource = e.target.src; var newSrc = clickedImageSource.replace("small", "medium"); var featuredImage = document.querySelector("#featured img"); featuredImage.src = newSrc; featuredImage.title = e.target.title; } }); var img = document.getElementById("figcaption"); img.addEventListener("mouseover",function (event) { img.className = "featured figcaption"; }); img.addEventListener("mouseout", function (event) { img.className = "featured figcaption"; var element = document.getElementById('figcaption'); element.style.opacity = "0.9"; element.style.filter = 'alpha(opacity=0%)'; }); Thanks for any advice and hopefully I can pay it forward for someone else!
I think it causes you the problem. The JS is getElementById, but there's no ID is call figcaption. var img = document.getElementById("figcaption");
The problem is that you are trying to use getElementById to find something with the id of figcaption; nothing on the page has an id of figcaption, so getElementById returns null. There are a few ways you could fix it: Add an id to your <figcaption> element: <figcaption id="figcaption"> Instead of using getElementById, use getElementsByTagName: document.getElementsByTagName('figcaption')[0];. (getElementsByTagName always returns a collection of elements, the [0] grabs the first, and in this case only, one in the collection). Instead of using getElementById, use querySelector like you did to find the featured image element: document.querySelector("#featured figcaption"); This last approach of using querySelector is what I would recommend in this situation; other times it might be better to add an id to the element. const thumbs = document.getElementById("thumbnails"); const featuredImage = document.querySelector("#featured img"); const caption = document.querySelector("#featured figcaption"); thumbs.addEventListener("click", function (e) { if (e.target.nodeName.toLowerCase() == 'img') { var clickedImageSource = e.target.src; // for the purposes of this demo, I'm using a placeholder // image service so I need to change the size slightly differently let newSrc = clickedImageSource.replace("50x50", "350x150"); //var newSrc = clickedImageSource.replace("small", "medium"); featuredImage.src = newSrc; caption.textContent = e.target.title; } }); caption.addEventListener("mouseover",function (event) { caption.className = "featured figcaption"; }); caption.addEventListener("mouseout", function (event) { caption.className = "featured figcaption"; // I changed the value to .5 instead of .9 because with such small // text the opacity change is barely perceivable. caption.style.opacity = "0.5"; // This is not needed, this was the old way IE used to do it, // IE < 9 needed it, but IE < 9 is no longer relevant. Just use opacity. //element.style.filter = 'alpha(opacity=0%)'; }); <header> <h2>Share Your Travels</h2> <nav><img src="http://via.placeholder.com/50x50?text=Menu"></nav> </header> <main> <figure id="featured"> <img src="http://via.placeholder.com/350x150" title="Battle"> <figcaption>Battle</figcaption> </figure> <div id="thumbnails"> <img src="http://via.placeholder.com/50x50" title="Battle"> <img src="http://via.placeholder.com/50x50/ff0000/ffffff" title="Luneburg"> <img src="http://via.placeholder.com/50x50/00ff00/ffffff" title="Bermuda"> <img src="http://via.placeholder.com/50x50/0000ff/ffffff" title="Athens"> <img src="http://via.placeholder.com/50x50/000000/ffffff" title="Florence"> </div> </main> A few things to note about my version, I used let and const instead of var. Both let and const are well supported these days and should be used instead of var unless you need to support very old browsers. I also only query for the caption and featured image elements once and store them in the scope above the click handler, this allows the code inside the click handler to have access to them via closure. This makes everything slightly more efficient since you don't have to query the DOM to find them each time the click handler runs. In this case the performance gain is moot but it is good to be in the habit of writing code as efficiently as possible so you don't have to think about it when it does matter. Images are void elements, meaning they can't have any content, so you don't need a closing tag. For this reason I used bare <img> tags instead of self-closing <img /> tags. Self-closing images were only ever needed in XHTML, since it was XML, which has a more rigid syntax than HTML. Another thing to note, you don't need the type="text/javascript" on your <script> tags, it just takes up extra space and doesn't really do anything. I don't understand what you are trying to do with the mouseover and mouseout handlers. Currently what your code does is: When the mouse moves over the caption, the featured and figcaption classes are added to the caption. When the mouse leaves the caption, the featured and figcaption classes are again added to the caption and its opacity is set to 0.9, effectively permanently. I cleaned it up a little in my example to make it more obvious that is what is happening.
Jquery toggle img attribute
I am trying to toggle images from the thumbnail to the feature image when the thumb nail is clicked. Currently when its clicked the images will swap but I cant get them to swap back with the thumb nail is clicked on again. I've tried using toggle but when the thumb nail is clicked on it would remove the image completely and I couldnt get any image to return. Currently this will switch the images but not switch or toggle them back on click. $(".browseTable").on('click', 'td', function () { var thumbNail = $(this).parent('tr').find('img').attr('src'); var feature = $('#featureImg img').attr('src'); $('#featureImg img').fadeOut(400, function () { $(this).fadeIn(400)[0].src = thumbNail; }); });
You can use data for store source string and toggling images preview on : https://jsfiddle.net/5kxf65Lx/ <img src="source1.jpg" data-srcfirst="source1.jpg" data-srcsecond="source2.jpg" /> <script type="text/javascript"> $('img').click(function(){ var loaded = $(this).attr('src') var first = $(this).data('srcfirst') var second = $(this).data('srcsecond') if(loaded == first){ $(this).attr('src' , second) } else { $(this).attr('src' , first) } })
Try this. When the parent is clicked we toggle both children. The large version starts off hidden. <div class="toggle js-toggle"> <img src="http://www.placehold.it/100x100" alt="" class="toggle__thumb js-toggle-image"/> <img src="http://www.placehold.it/500x500" alt="" class="toggle__active js-toggle-image" style="display: none" /> </div> The jQuery $('.js-toggle').on('click', function() { $(this).find('.js-toggle-image').toggle(); }); https://jsfiddle.net/uoLv2nkh/1/ Or an only CSS way if you only care about when the user is clicking. https://jsfiddle.net/uoLv2nkh/
You can achieve your target via setting src of image in css. .imageOne{ content:url(YOUR SOURCE); } .imageTwo{ content:url(YOUR SOURCE); } add class to your image element in start check if element exist by either class if exist toggle() to another, this will change the image back to another. And use toggle() like following example $(".browseTable").on('click', 'td', function () { //var thumbNail = $(this).parent('tr').find('img').attr('src'); //var feature = $('#featureImg img').attr('src'); //$('#featureImg img').fadeOut(400, function () { // $(this).fadeIn(400)[0].src = thumbNail; //}); $('#featureImg img').find('.imageOne, .imageTwo').toggle(); }); I am able to use toggle simply to change one element to another. etc. hope it will help you. Is it possible to set the equivalent of a src attribute of an img tag in CSS?
Get href and use as identifier jQuery
Currently I am trying to implement a hover effect for an image map. I swap the image on hover, the replcement image have that section of the map filled with a 'hover' color. <map name="Map"> <area id="france" shape="poly" coords="98,133,123,129,151,116,165,129,188,140,181,156,175,167,177,176,181,195,171,203,153,201,145,209,110,196,119,171,110,149,94,141" href="/page/france"> <area id="england" shape="poly" coords="94,119,114,115,139,116,150,100,130,69,117,75,119,89,115,106" href="/page/england"> <area id="wales" shape="poly" coords="118,87,112,107,99,100,109,86" href="/page/wales"> // many more areas // </map> jQuery $('#england').hover( function() { $('img').attr('src', '/lib/img/layout/map-en.gif'); }, function() { $('img').attr('src', '/lib/img/layout/map.gif'); } ); It works very nicely. The problem is I have many areas within my image map. Is there a way with jQuery of getting the last part of the href from a link and putting it into a dynamic working variable? Example logic: var identifier = area/href/this $(identifier).hover( function() { $('img').attr('src', '/lib/img/layout/map-'+identifier+'.gif'); }, function() { $('img').attr('src', '/lib/img/layout/map.gif'); } );
You can use this : $('area').hover(function(){ $('img').attr('src', '/lib/img/layout/map-'+this.href.split('/').pop().slice(0,2) +'.gif'); }, function(){ $('img').attr('src', '/lib/img/layout/map.gif'); }); this.href.split('/').pop().slice(0,2) takes the first 2 characters of the last token of the href of the hovered area. You could also give to your areas more normalized identifiants (like "en", "fr") so you wouldn't have to do this extraction.
Using the answer of dystroy and answering your doubt about getting only the end of the href you can use string split: $("#france").attr('href').split("/")[2] The [2] is to get the result that is the land name (in the example: france) Instead of using the 2 you can also first store in a variable and then get the last item using length: var tmp = $('#france').attr('href').split("/"); tmp[tmp.length-1]; It will print the last item of the href always. In this case "france"
onmouseover function Javascript
I am having a problem with changing onmouseover and onmouseout attributes on dynamic pictures. The way i want it to work is whenever i put my mouse over images the images must change and when i take my mouse away it must be changed to the original picture. and whenever i select any image, that image must be changed to the image which was displayed while moving the mouse across the image. and when i select any other image the same process must take place but the previous image that was changed must be changed back to the original picture. I have accomplished all of the above but my problem is when i select multiple pictures and put my mouse over images that were previously selected, those images do not change (onmouseover attribute does not work on them anymore). <script language="javascript"> function changeleft(loca){ var od='' var imgs = document.getElementById("leftsec").getElementsByTagName("img"); for (var i = 0, l = imgs.length; i < l; i++) { od=imgs[i].id; if(od==loca){ imgs[i].src="images/"+od+"_over.gif"; imgs[i].onmouseover=""; imgs[i].onmouseout=""; }else{ od = imgs[i].id; imgs[i].src="images/"+od+".gif"; this.onmouseover = function (){this.src="images/"+od+"_over.gif";}; this.onmouseout = function (){this.src="images/"+od+".gif";}; } } } </script> <div class="leftsec" id="leftsec" > <img id='wits' class="wits1" src="images/wits.gif" onmouseover="this.src='images/wits_over.gif'" onmouseout="this.src='images/wits.gif'" onclick="changeleft(this.id)" /><br /> <img id='city' class="city1" src="images/city.gif" onmouseover="this.src='images/city_over.gif'" onmouseout="this.src='images/city.gif'" onclick="changeleft(this.id)" /><br /> <img id='organise' class="city1" src="images/organise.gif" onmouseover="this.src='images/organise_over.gif'" onmouseout="this.src='images/organise.gif'" onclick="changeleft(this.id)" /><br /> <img id='people' class="city1" src="images/people.gif" onmouseover="this.src='images/people_over.gif'" onmouseout="this.src='images/people.gif'" onclick="changeleft(this.id)" /><br /> </div>
I'd say you don't need the lines that are resetting the onmouseover events. There's no need to rewrite the onmouseover events - all you want to change is the img src attribute. As Adam mentions, there's more modern ways to do this using jQuery - look at: http://code.google.com/p/jquery-swapimage/ For example.