Image Rollovers by <img> and <a> events - javascript

I was watching a Video tutorial according to the author CODE #2 should be used, but instead I changed it a little bit to CODE #1
So whats the difference in both of codes ,both perform the same tasks ,any technical or good practice here ?
CODE #1:
Used eventhandlers MouseOver and MouseOutof of tag
<a href="http://www.google.com" >
<img alt="arrow" name="ArrowImage"
onmouseover="document.ArrowImage.src='Images/arrow_on.gif'"
onmouseout="document.ArrowImage.src='Images/arrow_off.gif'"
src="Images/arrow_off.gif" />
</a>
CODE #2:
Used eventhandlers MouseOver and MouseOut of tag
<a href="http://www.google.com"
onmouseover="document.arrow.src='images/arrow_on.gif'"
onmouseout="document.arrow.src='images/arrow_off.gif'">
<img src="images/arrow_off.gif" width="147" height="82"
name="arrow" alt="arrow" />
</a>

If there's no formatting or additional content inside <a>, you can use either and it won't make a difference.
If there is CSS formatting or additional content within the link, the boundary of the <a> might differ from the boundary of the img. In this case it depends on the actual intent: Do you want to change the image source only when hovering the image or also when hovering the remainder of the link.
But since you're asking for good practice: It is recommended to not use inline JavaScript, i.e. don't mix HTML and JavaScript. When applying good practice you'd probably catch the mouse events in a separate <script> at the bottom of your HTML document or define a style using the CSS :hover pseudo class.

In the first example, the onmouseover and onmouseout events are bound to the <img> tag, so mousing inside the <img> activates them. In the second example, they're bound to the <a> tag in which the <img> is contained.
For your two examples, the result will be identical because the <img> is the only element inside the <a> tag.
However, if more text was included inside the <a> tag and the events bound to the <img> only, the rollover effect wouldn't occur when mousing over the text.
For example:
<a href="http://www.google.com" >
This is some text explaining the image. If you mouse over it, the rollover won't change.
<img alt="arrow" name="ArrowImage"
onmouseover="document.ArrowImage.src='Images/arrow_on.gif'"
onmouseout="document.ArrowImage.src='Images/arrow_off.gif'"
src="Images/arrow_off.gif" />
</a>
<a href="http://www.google.com"
onmouseover="document.arrow.src='images/arrow_on.gif'"
onmouseout="document.arrow.src='images/arrow_off.gif'">
This is some text explaining the image. If you mouse over it, the rollover WILL change.
<img src="images/arrow_off.gif" width="147" height="82"
name="arrow" alt="arrow" />
</a>

Either works fine. It's a matter of what you want to do.
If for instance you had text as well, you'd choose option 2, because the text would be right after <img> and before </a>.
Generally, you want stay away from binding directly to images, because you usually end up wanting to put more things with that image (such as text, or other containers).

It's generally not considered good practice to use 'inline javascript' the way you're doing here. This makes code very difficult to read and and less maintainable in the long run. Using unobtrusive javascript defined in a separate javascript file is the way to go. An example of that using jquery would be:
// defined in application.js for example:
$("img").hover(function onmouseover(){
$(this).attr("src", "Images/arrow_on.gif");
}, function onomouseout(){
$(this).attr("src", "Images/arrow_off.gif");
});
As far as the differences between the two approaches, the only difference is at what point the events get triggered. The first one causes the events to be triggered when the user mouses over the image, and the second one occurs when the user mouses over the anchor. The anchor, depending on it styles, could occupy a larger area than the image itself, so choosing between the two depends on the effect you want to produce.
As far as 'good practices', this example is really a bad usage of javascript, in other words you can accomplish the same thing using CSS Sprites.
For example, CSS:
/* use a more specific selector in your actual code */
a {
/* on state */
background: url(Images/arrow.gif) no-repeat 0 0;
}
a:hover {
/* default state */
background: url(Images/arrow.gif) no-repeat -50px 0;
}

Was the video from 1992?
You can achieve rollover effects with CSS alone, which is considerably better, e.g.
a#rollover {
background: url("normal.jpg") no-repeat 0 0;
}
a#rollover:hover {
background: url("rollover.jpg") no-repeat 0 0;
}
Better still, you can have both states as a single image, and just change the background position on hover, as described here.
If you want to use JavaScript to change an image source, then a) use unobtrusive JavaScript, and b) use jQuery for added simplicity.

First, roll over images are typically accomplished with CSS
See devdigital's answer for an example.
Second, if you are going to use JavaScript in the way you have in your code see Michael's example
Third, I would like to note that the attribute "name" is not a valid attribute for either of those elements in HTML5 and not at all (Read: HTML4) for the img element.
Finally, a preferred way to do this with with JS would be something like this:
HTML:
<a id="rollover" href="link.html"><img id="rolloverimage" src="image.jpg" width="100" height="100" alt="text"/></a>
JS:
var atag = document.getElementById('rollover');
atag.onmouseover = function() {
document.getElementById('rolloverimage').src = 'rollover.jpg';
}
atag.onmouseout = function() {
document.getElementById('rolloverimage').src = 'image.jpg';
}

Related

Odd behavior in jquery `.on('click')`

I've made a slider that displays media files (img,video and pdf), and those media files can be selected to do some operations with them (deleting & attaching), so anyways, initially I made a class called selected-media which had a shadow, this worked ok, but it was pretty ugly (you know, media files can change in aspect ratio and whatnot, and this shadow was applied on the div containing the actual <img>, <video>, not the media itself). So I decided to google some ways to make this shadow dynamic, so that it was applied not on the div but around the img itself.
To do that I followed the SO answer and did this:
.selected-media{
-webkit-filter: drop-shadow(12px 12px 25px darkturquoise);
filter: url(an_url);
-ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}
Now funnily, even though the url is always the same, this shadow IS dynamic somehow, and it does exactly what I wanted it to. This is good because I'm using flask for the backend and dynamically feeding an url into css is a big pain in the butt.
However there was a problem, a weird one as well, and that presented itself when I added the pdf support.
Here is the structure of the slider:
<div id="media-slider">
<div class="selectable selected-media" id="single-media-5">
<img class="single-media" src="img-url">
</div>
<div class="selectable selected-media" id="single-media-26">
<div style="height: 100px; text-align:center">
<img class="single-media" src="\\static\\resources\\pdf-placeholder-icon.png" >
<p>'+ pdf_name +'</p>
</div>
</div>
</div>
And this is the weird behavior i am talking about:
This is the expected result
However if I click on the text this consistently happens (not sure if you can see it, but the shadow is applied to the text as well)
And this is the code that handles those events:
$(document).on("click","#media-slider > div.selectable", function (event) {
if (!event.currentTarget.classList.contains("selected-media")){
event.currentTarget.classList.add("selected-media");
}
else {
event.currentTarget.classList.remove("selected-media");
}
});
Now, the funny thing is that jQuery is not adding any class to the <p> element, the html looks identical in the two cases shown above. I'm not sure what is happening here, of course if you click on the text it should still apply the effect on the img, but just there.

HTML OnMouseOver with list image

I'm really new to all of this so if anybody can help much appreciated - I have 2 questions.
First I tried:
<a href="Streaming.html">
<li>
<img Src="Streaming.jpg" onmouseover="this.src='HoverStreaming.jpg'; this.height='90px';"; onmouseout="this.src='Streaming.jpg'; this.height='75px';"; width="140" height="75">
</li>
</a>
This worked for changing the image but doesn't seem to work for the height.
Since it's in a list and div is block level I am not using it however I tried putting an ID on the image and using JQuery connecting my html to my other file using <script type="text/javascript" src="ArchDragonJQuery.js"></script> and using:
$(document).ready(function(){
$("#Bigger").mouseenter(function(){
$(this).animate({
height: "+=30px"
});
});
$("#Bigger").mouseleave(function(){
$(this).animate({
height: "-=30px"
});
});
});
I have tried a few things instead of ID and I still cannot seem to get it to do anything.
So I am wondering A- how can I make the size increase while hovering over, and B- is my jQuery code simply not being correctly linked to the html? if so how do I fix this?
Thanks
From what I can tell, you want an image to have a height of 75px and, when it is hovered over, you want the image to change and have a height of 90px. You can accomplish the 'growing' effect using only CSS using the hover selector.
.hoverGrow img {height:75px; transition:height .4s ease;}
.hoverGrow img:hover {height:90px;}
<a href="Streaming.html">
<li class="hoverGrow">
<img src="http://placekitten.com/g/200/300" onmouseover="this.src='http://placekitten.com/g/300/200';"; onmouseout="this.src='http://placekitten.com/g/200/300';">
</li>
</a>
this.height is always the height in pixels. It's a number without units. You'd want to do this.height=75. That'll change the height attribute on the element itself. (I think you could probably do this all without script and use CSS only, you can see an example here and here).
I'm not sure what's wrong with your jQuery case. Make sure the ID has the same capitalization - you have an unusual capitalization style going on in your example. IDs are case sensitive in most browsers. $("#Bigger") will match <img id="Bigger"> but not <img id="bigger">. You also can't have multiple elements with the same ID - make sure there is only one id="Bigger".
I redid your code and it all works out. Hopefully you can learn just by looking at what I did. Your a tag needs to be inside your li tag. Your Src needs to be src. keep the code clean. I know I am typing like shit but I am lazy now :D Click the link to the codepen
Hope this helps.
$('img.image').mouseenter(function(){
$(this).animate({height: '+=30'});
});
$('img.image').mouseleave(function(){
$(this).animate({height: "-=30"});
});
http://codepen.io/anon/pen/VYLezx

How to ensure CSS :hover is applied to dynamically added element

I have a script that adds full images dynamically over thumbnails when you hover over them. I've also given the full images a CSS :hover style to make them expand to a larger width (where normally they are constrained to the dimensions of the thumbnail). This works fine if the image loads quickly or is cached, but if the full image takes a long time to load and you don't move the mouse while it's loading, then once it does appear it will usually stay at the thumbnail width (the non-:hover style) until you move the mouse again. I get this behavior in all browsers that I've tried it in. I'm wondering if this is a bug, and if there's a way to fix or work around it.
It may be worth noting that I've also tried to do the same thing in Javascript with .on('mouseenter'), and encountered the same problem.
Due to the nature of the issue, it can be hard to reproduce, especially if you have a fast connection. I chose a largish photo from Wikipedia to demonstrate, but to make it work you might have to change it to something especially large or from a slow domain. Also note that you may have to clear the cache for successive retries.
If you still can't reproduce, you can add an artificial delay to the fullimage.load before the call to anchor.show().
HTML:
<img id="image" src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Cairo_International_Stadium.jpg/220px-Cairo_International_Stadium.jpg" />
CSS:
.kiyuras-image {
position: absolute;
top: 8px;
left: 8px;
max-width: 220px;
}
.kiyuras-image:hover {
max-width: 400px;
}
JS:
$(function () {
var fullimageurl = 'http://upload.wikimedia.org/wikipedia/commons/3/32/Cairo_International_Stadium.jpg';
var fullimage = $('<img/>')
.addClass('kiyuras-image')
.load(function () {
anchor.show();
});
var anchor = $('<a/>').hide().append(fullimage);
$('body').prepend(anchor);
$("#image").on('mouseenter', function () {
fullimage.attr('src',fullimageurl);
$(this).off('mouseenter');
});
});
JS Bin
Updated JS Bin with 1.5-second delay added (Hopefully makes issue clearer)
Again: Reproducing the issue involves clearing your cache of the large image, and then hovering over the original image to initial the loading of large image, then not moving your mouse while it's loading. Intended behavior is for the large image to properly take on the :hover pseudo-class when it eventually loads. Issue I see when it takes longer than ~0.75 secs to load is that it does not take on :hover until you jiggle the mouse a little.
Edit: See my comments on #LucaFagioli's answer for further details of my use case.
Edit, the sequel: I thought I already did this, but I just tried to reproduce the issue in Firefox and I couldn't. Perhaps this is a Chrome bug?
Most browsers update their hover states only when the cursor moves over an element by at least one pixel. When the cursor enters the thumbnail's img it gets hover applied and runs your mouseenter handler. If you keep your cursor still until the full-sized image loads, your old img (the thumbnail) will keep the hover state and the new one won't get it.
To get it working in these browsers, move the hover pseudo-class to a common parent element in the CSS; for example, enclose both imgs in a span.
If the selectors are correct, CSS will be applied to all elements, dynamic or otherwise. This includes all pseudo classes, and will change as attributes in the DOM change.
[Edit: while my explanation might be of interest, pozs' solution above is nicer, so I suggest using that if you can.]
The hover pseudo-class specification is quite relaxed concerning when it should be activated:
CSS does not define which elements may be in the above states,
or how the states are entered and left. Scripting may change
whether elements react to user events or not, and different
devices and UAs may have different ways of pointing to, or
activating elements.
In particular, it is not being activated when you update the visibility of the anchor element on load.
You can get around this fairly easily: copy the hover styles to a class, intercept the cursor moving over the element that it will eventually cover, and based on that add or remove your class from the element.
Demo: JS Bin (based on your delayed example).
Javascript:
$("#image")
.on('mouseenter', function () {
fullimage.attr('src',fullimageurl).toggleClass('mouseover', true);
$(this).off('mouseenter');
})
.mouseleave(function() {
fullimage.toggleClass('mouseover', false);
});
CSS:
.kiyuras-image:hover, .kiyuras-image.mouseover {
max-width: 400px;
}
TL;DR: You cannot rely on :hover applying to dynamically added elements underneath the cursor. However, there are workarounds available in both pure CSS and Javascript.
I'm upvoting both Jordan Gray and posz' answers, and I wish I could award them both the bounty. Jordan Gray addressed the issue re: the CSS specification in a somewhat conclusive way and offered (another) working fix that still allowed for :hover and other CSS effects like transitions, except on load. posz provided a solution that works even better and avoids Javascript for any of the hover events; I provide essentially the same solution here, but with a div instead of a span. I decided to award it to him, but I think Jordan's input was essential. I'm adding and accepting my own answer because I felt the need to elaborate more on all of this myself. (Edit: Changed, I accepted posz')
Jordan referenced the CSS2 spec; I will refer instead to CSS3. As far as I can tell, they don't differ on this point.
The pseudo-class in question is :hover, which refers to elements that the user has "designated with a pointing device." The exact definition of the behavior is deliberately left vague to allow for different kinds of interaction and media, which unfortunately means that the spec does not address questions like: "Should a new element that appears under the pointing device have this pseudo-class applied?" This is a hard question to answer. Which answer will align with user intent in a majority of cases? A dynamic change to a page the user is interacting with would normally be a result of ongoing user interaction or preparation for the same. Therefore, I would say yes, and most current browsers seem to agree. Normally, when you add an element under the cursor, :hover is immediately applied. You can see this here: The jsbin I originally posted. Note that if there's a delay in loading the larger image, you may have to refresh the page to get it to work, for reasons I'll go into.
Now, there's a similar case where the user activates the browser itself with the cursor held stationary over an element with a :hover rule; should it apply in that case? The mouse "hover" in this case was not a result of direct user interaction. But the pointing device is designating it, right? Besides, any movement of the mouse will certainly result in an unambiguous interaction. This is a harder question to answer, and browsers answer it in different ways. When you're activating them, Chrome and Firefox do not change :hover state until you move the mouse (Even if you activated them with a click!). Internet Explorer, on the other hand, updates :hover state as soon as it's activated. In fact, it updates it even when it's not active, as long as it's the first visible window under the mouse. You can see this yourself using the jsbin linked above.
Let's return to the first case, though, because that's where my current issue arises. In my case, the user hasn't moved the mouse for a significant length of time (over a second), and an element is added directly underneath the cursor. This could more easily be argued to be a case where user interaction is ambiguous, and where the pseudo-class should not be toggled. Personally, I think that it should still be applied. However, most browsers do not seem to agree with me. When you hover over the image for the first time and then do not move your mouse in this jsbin (Which is the one I posted in my question to demonstrate the issue, and, like the first one, has a straightforward :hover selector), the :hover class is not applied in current Chrome, Opera, and IE. (Safari also doesn't apply it, but interestingly, it does if you go on to press a key on the keyboard.) In Firefox, however, the :hover class is applied immediately. Since Chrome and Firefox were the only two I initially tested with, I thought this was a bug in Chrome. However, the spec is more or less completely silent on this point. Most implementations say nay; Firefox and I say aye.
Here are the relevant sections of the spec:
The :hover pseudo-class applies while the user designates an element with a pointing device, but does not necessarily activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not that do not support interactive media do not have to support this pseudo-class. Some conforming user agents that support interactive media may not be able to support this pseudo-class (e.g., a pen device that does not detect hovering).
[...]
Selectors doesn't define if the parent of an element that is ‘:active’ or ‘:hover’ is also in that state.
[...]
Note: If the ‘:hover’ state applies to an element because its child is designated by a pointing device, then it's possible for ‘:hover’ to apply to an element that is not underneath the pointing device.
So! On to the workarounds! As several have zealously pointed out in this thread, Javascript and jQuery provide solutions for this as well, relying on the 'mouseover' and 'mouseenter' DOM events. I explored quite a few of those solutions myself, both before and after asking this question. However, these have their own issues, they have slightly different behavior, and they usually involve simply toggling a CSS class anyway. Besides, why use Javascript if it's not necessary?
I was interested in finding a solution that used :hover and nothing else, and this is it (jsbin). Instead of putting the :hover on the element being added, we instead put it on an existing element that contains that new element, and that takes up the same physical space; in this case, a div containing both the thumbnail and the new larger image (which, when not hovered, will be the same size as the div and thumbnail). This would seem to be fairly specific to my use case, but it could probably be accomplished in general using a positioned div with the same size as the new element.
Adding: After I finished composing this answer, pozs provided basically the same solution as above!
A compromise between this and one of the full-Javascript solutions is to have a one-time-use class that will effectively rely on Javascript/DOM hover events while adding the new element, and then remove all that and rely on :hover going forward. This is the solution Jordan Gray offered (Jsbin)
Both of these work in all the browsers I tried: Chrome, Firefox, Opera, Safari, and Internet Explorer.
From this part of your question: "This works fine if the image loads quickly or is cached, but if the full image takes a long time to load and you don't move the mouse while it's loading,"
Could it be worth while to "preload" all of the images first with JavaScript. This may allow all of the images to load successfully first, and it may be a little more user friendly for people with slower connections.
You could do something like that : http://jsfiddle.net/jR5Ba/5/
In summary, append a loading layout in front of your image, then append a div containing your large image with a .load() callback to remove your loading layer.
The fiddle above has not been simplified and cleaned up due to lack of time, but I can continue to work on it tomorrow if needed.
$imageContainer = $("#image-container");
$image = $('#image');
$imageContainer.on({
mouseenter: function (event) {
//Add a loading class
$imageContainer.addClass('loading');
$image.css('opacity',0.5);
//Insert div (for styling) containing large image
$(this).append('<div><img class="hidden large-image-container" id="'+this.id+'-large" src="'+fullimageurl+'" /></div>');
//Append large image load callback
$('#'+this.id+'-large').load(function() {
$imageContainer.removeClass('loading');
$image.css('opacity',1);
$(this).slideDown('slow');
//alert ("The image has loaded!");
});
},
mouseleave: function (event) {
//Remove loading class
$imageContainer.removeClass('loading');
//Remove div with large image
$('#'+this.id+'-large').remove();
$image.css('opacity',1);
}
});
EDIT
Here is a new version of the fiddle including the right size loading layer with an animation when the large picture is displayed : http://jsfiddle.net/jR5Ba/6/
Hope it will help
Don't let the IMG tag get added to the DOM until it has an image to download. That way the Load event won't fire until the image has been loaded. Here is the amended JS:
$(function () {
var fullimageurl = 'http://upload.wikimedia.org/wikipedia/commons/3/32/Cairo_International_Stadium.jpg';
var fullimage = $('<img/>')
.addClass('kiyuras-image')
.load(function () {
anchor.show(); // Only happens after IMG src has loaded
});
var anchor = $('<a/>').hide();
$('body').prepend(anchor);
$("#image").on('mouseenter', function () {
fullimage.attr('src',fullimageurl); // IMG has source
$(this).off('mouseenter');
anchor.append(fullimage); // Append IMG to DOM now.
});
});
I did that and it worked on Chrome (version 22.0.1229.94 m):
I changed the css as that:
.kiyuras-image{
position: absolute;
top: 8px;
left: 8px;
max-width: 400px;
}
.not-hovered{
max-width: 220px;
}
and the script this way:
$(function(){
var fullimageurl = 'http://upload.wikimedia.org/wikipedia/commons/3/32/Cairo_International_Stadium.jpg';
var fullimage = $('<img/>')
.addClass('kiyuras-image')
.load(function () {
anchor.show();
});
var anchor = $('<a/>').hide().append(fullimage);
$('body').prepend(anchor);
$('.kiyuras-image').on('mouseout',function(){
$(this).addClass('not-hovered');
});
$('.kiyuras-image').on('mouseover',function(){
$(this).removeClass('not-hovered');
});
$("#image").one('mouseover', function(){
fullimage.attr('src',fullimageurl);
});
});
Basically I think it's a Chrome bug in detecting/rendering the 'hover' status; in fact when I tried to simply change the css as:
.kiyuras-image{
position: absolute;
top: 8px;
left: 8px;
max-width: 400px;
}
.kiyuras-image:not(:hover) {
position: absolute;
top: 8px;
left: 8px;
max-width: 220px;
}
it still didn't worked.
PS: sorry for my english.
I'm not 100% sure why the :hover declaration is only triggered on slight mouse move. A possible reason could be that technically you may not really hover the element. Basically you're shoving the element under the cursor while it is loading (until the large image is completely loaded the A element has display: none and can therefore impossible be in the :hover state). At the same time, that doesn't explain the difference with smaller images though...
So, a workaround is to just use JavaScript and leave the :hover statement out of the equation. Just show the user the two different IMG elements depending on the hover state (toggles in JavaScript). As an extra advantage, the image doesn't have to be scaled up and down dynamically by the browser (visual glitch in Chrome).
See http://jsbin.com/ifitep/34/
UPDATE: By using JavaScript to add an .active class on the large image, it's entirely possible to keep using native CSS animations. See http://jsbin.com/ifitep/48

Javascript Gallery onmouseUp with "#" link without jumping to top of page

I realize that this is probably an "old school" way of doing this, but I finally got my gallery to work with one exception. If the gallery is located lower on the page, the "#" link on the thumbnails causes the page to jump the top. Is there a better way to create this gallery?
http://pacmill.bigrigmedia.com/cms/portfolio-detail-test3.html
Thanks in advance!
Adding a return false will usually stop the page from jumping to the top when clicking on a # link.
<img src="..." />
For your problem, I would go with Shawn's solution and just use CSS. So delete all of the links around the images and add this to your document:
<style> img{cursor:pointer;} #Display{cursor:auto;} </style>
The second entry (#Display) is to make sure your main image does not get the pointer cursor. It would be better to just drop a class on each of your images and then assign the cursor to images with that class. That would look like so:
<style> img.myImage{cursor:pointer;} </style>
<img class="myImage" src="...">
I'm guessing you're using the anchor tag in order to get the hand icon on hover. You could get the same effect by using CSS.
style="cursor: hand;"
This should create the same effect and avoid the problem of the anchor tag.
I strongly suggest you to don't use an anchor tag for that. JavaScript events can be added to any DOM element, just like in:
<li class="click-to-expand">
<img src="..." />
</li>
And also, as some users already replied, you can use CSS pointer property to indicate a possible user interaction when hovering the clickable interface item.
.click-to-expand{
cursor:pointer;
}
Remember to keep it accessible by providing a valid URL to access the content in case it's necessary (no javascript fallback).

Ignore mouse interaction on overlay image

I have a menu bar with hover effects, and now I want to place a transparent image with a circle and a "handdrawn" text over one of the menu items. If I use absolute positioning to place the overlay image above the menu item, the user will not be able to click the button and the hover effect will not work.
Is there any way to somehow disable mouse interaction with this overlay image so that the menu will keep on working just as before even though it's beneath an image?
Edit:
Because the menu was generated with Joomla I could not tweak just one of the menu items. And even if I could, I did not feel a Javascript solution was appropriate. So in the end I "marked" the menu item with an arrow outside the menu-item element. Not as nice as I had wanted it to be, but it worked out okey anyway.
The best solution I've found is with CSS Styling:
#reflection_overlay {
background-image:url(../img/reflection.png);
background-repeat:no-repeat;
width: 195px;
pointer-events:none;
}
pointer-events attribute works pretty good and is simple.
So I did this and it works in Firefox 3.5 on Windows XP. It shows a box with some text, an image overlay, and a transparent div above that intercepts all clicks.
<div id="menuOption" style="border:1px solid black;position:relative;width:100px;height:40px;">
sometext goes here.
<!-- Place image inside of you menu bar link -->
<img id="imgOverlay" src="w3.png" style="z-index:4;position:absolute;top:0px;left:0px;width:100px;height:40px;" \>
<!-- Your link here -->
<a href="javascript:alert('Hello!')" >
<div id="mylinkAction" style="z-index:5;position:absolute;top:0px;left:0px;width:100px;height:40px;">
</div>
</a>
</div>
What I've done:
I've crafted a div and sized it to be what a menu option could be sized to, 100x40px (an arbitrary value, but it helps with illustrating the sample).
The div has an image overlay, and a link overlay. The link contains a div sized to be the same as the 'menuOption' div. This way a user click is captured across the whole box.
You will need to provide your own image when testing. :)
Caveat:
If you expect your menu button to respond to the user interaction (for example, changing color to simulate a button), then you will need extra code attached to the javascript you will invoke on the tag, this extra code could address the 'menuOption' element through the DOM and change it's color.
Also, there is no other way I know of that you can take a click event, and have it register on an element underneath a visible page element. I've tried this as well this summer, and found no other solution but this.
Hope this helps.
PS:
The writeup on events at quirksmode went a long way to help me understand how events behave in browsers.
Give the button a higher z-index property than the hand-drawn image:
<img src="hand_drawn_image.gif" style="z-index: 4">
however, make sure you test it in all major browsers. IE interprets z-index differently from FF.
For somebody to come up with more details, you would have to post more info, a link would be best.
Building on what Pekka Gaiser said, I think the following will work. Taking his example and reworking it:
<a href="#" style="z-index: 5">
<!-- Place image inside of you menu bar link -->
<img src="hand_drawn_image.gif" style="z-index: 4">
<!-- Your link here -->
</a>
Here you should be able to place an event on the underlying a-tag and, unless your image has an event, initiates a capture (!IE browsers) and then kills propagation of the event.
If you need a bit more help, let us know a bit more about the situation.
If the image will be statically positioned, you can capture the click event from the image as it bubbles up, by placing the img tag inside the menu item element.
<div onclick="menuclick()">
<img src="overlay.png" style="position:absolute;" />
</div>

Categories

Resources