Iterate over area elements with $.each() or for loop - javascript

Is there a way to avoid repeating code when iterating over area elements with Jquery? or an easier way with plain javascript? A snippet of the HTML:
<img id="img1" src="image.png" width="400px" height="400px" usemap="#area_click"title="click to shade different areas" />
<map name="area_click">
<area href="" shape="poly" coords="33,149,53,151,49,183,45,205,27,197,29,171" alt="area1" >
<area href="" shape="poly" coords="157,148,161,168,161,201,143,204,139,180,137,152" alt="area2" >
<area href="" shape="poly" coords="51,144,55,126,57,114,41,88,32,112,32,140" alt="area3" >//...35 more areas follow...
</map>
I have tried...
Create array from map children.
var kids=$("map[name*='area_click']").children();
Loop through the array.
for (var k=0;k<kids.length;k++){
kids[k].click(function(event){
event.preventDefault();
$("#" + AreaArray[k]).fadeToggle(500).fadeTo(300,opacityArray[k]);});}
I thought I was missing something about the array-like object created by children().
So I tried...
1.Create array from map children. Then use eq() to grab references to the DOM elements in the array.
var kids=$("map[name*='area_click']").children();
var kidsArray = kids.eq();
2.Loop through the array.
for (var k=0;k<kidsArray.length;k++){
kidsArray[k].click(function(event){
event.preventDefault();
$("#" + AreaArray[k]).fadeToggle(500).fadeTo(300,opacityArray[k]);});}
Also tried using $.each and find() instead of children(). But it seems $.each() cannot digest area elements. The following generates a type error in the jquery.min script in the Firebug console.
TypeError: t is undefined
...nction(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"...
var kids=$("map[name*='area_click']").find("area");
var k=0;
$.each(kids.eq(k)).click(function(event){
event.preventDefault();
$("#" + areaArray[k]).fadeToggle(500).fadeTo(300,opacityArray[k]);
k++;
});
I'm sure I am doing something wrong in trying to pass a reference to the array to the for loop or $.each(), I just don't know what. Any help? Or am I going about the whole thing backwards?

Looks like a problem with the closure variable k, try
kids.each(function (k) {
$(this).click(function (event) {
event.preventDefault();
$("#" + AreaArray[k]).fadeToggle(500).fadeTo(300, opacityArray[k]);
});
})
Or
kids.click(function (event) {
event.preventDefault();
var k = kids.index(this)
$("#" + AreaArray[k]).fadeToggle(500).fadeTo(300, opacityArray[k]);
});

Related

How to browse area list in Javascript

I am trying to learn Javascript,
Can someone tell me if it is possible to browse an area List with Javascript ?
If yes how can I do it?
Here is my HTML Code:
<map name="rx" id="rx">
<area href="Link.gg" coords="137,92,25" shape="circle" alt="Blabla">
<area href="Link1.gg" coords="227,93,25" shape="circle" alt="Blabla1">
<area href="Link2.gg" coords="295,105,25" shape="circle" alt="Blabla2">
</map>
What is the JS Code to browse this ?
If it is possible I have got one more question,
HTML Code:
<area href="Exemple.gg" coords="295,105,25" shape="circle" alt="Unicorn">
How can I get the value of the href and the alt ?
( `var myvar = "Exemple.gg"; var myalt = "Unicorn";`)
I just want to get the text from the href and alt.
const areas = document.querySelectorAll('area'); // use more precise selector if needed
let myElement;
areas.forEach(el => {
if (!myElement && el.getAttribute('alt') === 'Red') {
myElement = el;
}
});
console.log(myElement)
To get area list under your map element use
var areaList = $("map#rx").find("area");
To get area attributes just use
var href=$("area").attr("href");
var alt=$("area").attr("alt");

How to fire JS function from area href

I have a image with a link map like this (generated in PHP):
<map name="map_bc-03" id="map_bc-03">
<area shape="circle" coords="166,28,12" href="#" onClick="changeCount('plus','bc-03');">
<area shape="circle" coords="166,82,11" href="#" onClick="changeCount('minus','bc-03');">
</map>
I am trying to fire a JS function called changeCount(type,product).
JS function purpose is to take the current value of a HTML element (<span>) and add 1 to it (x+1). JS function looks like:
function changeCount(type,product)
{
if ( type == "plus" )
{
$("#count_" + product).val() = $("count_" + product).val() + 1;
}
}
Problem is that 1/ the JS function is not fired with error message "ReferenceError: changeCount is not defined", which I do not understand why as clearly the function is defined....
Problem number 2/ the JS function itself causes a "ReferenceError: Invalid left-hand side expression in postfix operation" error (even though not fired)....
Any help greatly appreciated!
val() is for form elements. For <span> you need html() or text(). try this
function changeCount(type,product){
if ( type == "plus" ){
$("#count_" + product).text(function(index, val){
return parseInt(val)+1;
});
}
}
Use val(value); instead of using val() = value;.
Important thing is,
if your target selector is an input or any form element then use .val().
Otherwise, if it is any of div, span or any other non-form element then use .text() instead of .val(). Because, non-form elements don't have any values.
According to your question, you are targetting a <span>. So, I think you have to use .text().
function changeCount(type,product)
{
if ( type == "plus" )
{
$('#count_'+ product).text(Number($('#count_' + product).text()) + 1);
}
}
It should be
$("#count_" + product).val() = parseInt($("#count_" + product).val()) + 1;
"#" is missing while getting value and parseInt should be used.

toggle an image to a html map image by javascript

first of all I wanted to know if it is possible?
I want to change a picture inside a div while mouse is hover on the div to another picture which is a html imagemap.
if it is why this code does not work?
<script>
function chgImg(x) {
x.src = "2.jpg";
x.write('<img src="Untitled" width="320" height="427" border="0" usemap="#map" />');
x.write('<map name="map">');
x.write('<area shape="rect" coords="45,85,104,143" href="http://www.google.com" >');
x.write('<area shape="rect" coords="204,40,299,120" href="http://www.yahoo.com" >');
x.write('<area shape="rect" coords="51,296,121,368" href="http://www.imdb.com" >');
x.write('</map>');
}
function originImg(x) {
x.src = "1.jpg";
}
</script>
I changed quote , less than and greater than by html identities in order to evade nested quotes in the java script function.
thank you for your help.
Assuming x is an img element, the following should suffice :
HTML part:
<img onmouseover="chgImg" onmouseout= "originImg" src="1.jpg">
<map name="map">
<!--You map here-->
</map>
Javascript part
function chgImg(x) {
x.src = "2.jpg";
x.usemap = "map";
}
function originImg(x) {
x.src = "1.jpg";
delete x.usemap;
}
(Nota : not entirely sure about the last statement. Could be x.usemap = "" or x.usemap = null or x.usemap = undefined)
If you really need to dynamically construct a map for your img, I suggest you take a look at document.createElement and Node.appendChild, 2 functions that will allow you to add items to the DOM tree in a clean fashion.
I also recommend you use the Mozilla javascript documentation for the reference regarding these 2 DOM functions and all others, as I find it to be the most comprehensive and clear documentation for standart javascript objects and functions.

Click on image not working

For some reason I cannot click on this image to show the fancybox if I have "onmouseover" as a parameter:
<area onmouseover="toggleOverlay('SteWoz',1);" id="locSteWoz" alt="Test" class="fancybox" coords="24,51,236,244" href="http://www.google.com" rel="iframe" shape="rect" title="Test">
EDIT: This is what toggleOverlay does:
<script>
function toggleOverlay(name, newState){
var element = 'imgOverlay' + name;
var newDisplay
if (newState == 0) {newDisplay = 'none'}
if (newState == 1) {newDisplay = 'block'}
document.getElementById(element).style.display = newDisplay;
//document.getElementById(element).style.z-index = '5';
$(element).hide().fadeIn(4000);
}
</script>
If I remove "onmouseover" it works fine. How can I "fix" this?
James
First, this line :
$(element).hide().fadeIn(4000);
... doesn't really do anything because at this point element still need a proper sign (either # or .) to define the selector so in this case should be :
$("#" + element).hide().fadeIn(1000);
Second, if you are overlaying another image over the image that uses the image map, what I assume you are doing like in this JSFIDDLE,
... then there is nothing you can do to "make the overlay not respond to any clicks so that the image below can be clicked".
What you could do however, is to make the overlay image to use the same image map as the image below so, within your toggleOverlay() function, you could tweak this line
$("#" + element).hide().fadeIn(1000);
... into this
$("#" + element).hide().fadeIn(1000).attr("usemap", "#Map");
... assuming that your html looks like
<map name="Map" id="Map">
<area onmouseover="toggleOverlay('SteWoz',1);" id="locSteWoz" class="fancybox" shape="square" coords="0,0,415,319" href="{target}" title="title" alt="alt" />
</map>
... otherwise use the corresponding ID of the map tag.
See updated JSFIDDLE

jQuery not creating area tags

I'm trying to use jQuery to dynamically create an image map, and I ran into a weird behavior:
alert( $('<area />').size() ); // 1
alert( $('<area shape="circle" />').size() ); // 0
alert( $('<area />').attr("shape", "circle").size() ); // 1
In other words, I can't create an area tag all at once; if I say
$('<area shape="circle" coords="50,25,4" href="#" alt="foo" />')
then nothing is created. However, it works if I do it gradually, e.g.
$('<area />')
.attr("shape", "circle")
.attr("coords", "50,25,4")
.attr("href", "#")
.attr("alt", "foo");
I have no idea why this is, because I can create all kinds of other elements with attributes and content, e.g.
$('<div id="foo" />')
$('<div id="bar">Hello World!</div>')
so I'm not clear on why this isn't working. This isn't all that important since I can make it wirk by chaining calls to attr, but that's annoying and I'd like to understand this behavior.
An <area /> element is only defined inside an image map (i.e. <map> element). So essentially the following is failing (as this is what jQuery is doing with your markup):
var div = document.createElement('div');
div.innerHTML = '<area shape="circle" coords="50,25,4" href="#" alt="foo" />';
return div.childNodes; // this is empty, as the browser didn't allow
// the <area /> element inside the <div> element
It's just one of those things obviously the great jQuery has not accounted for (yet). In the meantime try:
var $area = $(
'<map><area shape="circle" coords="50,25,4" href="#" alt="foo" /></map>'
).contents();
// $area is the jQuery object for the newly created <area /> tag
$area.attr('coords'); // "50,25,4"
// etc

Categories

Resources