How should I use an image to trigger Javascript? - javascript

To have an image which acts as a javascript trigger there are quite a few options:
(EDIT: using inline css & javascript for simplifying the question)
Image in anchor tag:
<img src="pic.jpg" />
Img tag with properties:
<img style="cursor:pointer" onclick="myFunc();" />
Anchor tag with properties:
Possibly others as well. Is there a (convention|best practice|widely accepted|fail safe) way to go on with this?
I want a small image to act as a button to run certain Javascript or AJAX.
BTW, I've seen this but it's not what I'm looking for, he talks about header elements, not links.
Related: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

There is no convention on how to use onclick event.
But you should not use inline javascript. As we are in 2012 and a lot of javascript frameworks make your life easier.
Best for you if you move to a javascript library (eg jQuery):
<img src="pic.jpg" id="myPicture" />
<script type="text/javascript">
$(document).ready(function(){
$('#myPicture').on('click', function(){
alert('image clicked');
});
});
</script>
or plain javascript:
<img src="pic.jpg" id="myPicture" />
<script type="text/javascript">
window.onload = function(){
document.getElementById('myPicture').onclick = function(){
alert('image clicked');
};
};
</script>

If I were you I'd stick with your first choice with a few changes
<img src="pic.jpg" border="0" />
Reasons for this are as follows
href="#" still allows clickthrough if your myFunc fails
javascript:void(0) doesn't allow clickthrough
javascript:void(0) is cross-browser
javascript:void(0) still allows basic implied anchor tag behaviour
attribute/properties on the image tag will be recognised by most browsers but some older versions of IE may not like it
if you want to use a background image that's upto you, but it'll mean additional CSS to control height/width
Additionally, if you use jQuery or some other library, then I'd recommend doing it via
$(document).on('ready, function() {
$('#myAnchorId').on('click', myFunc);
});
Instead of doing via HTML props... just in case the user has JavaScript turned off

If you only going to use the image as an trigger, use the second option...
If you're going to use some more for the same thing, you can use an span to...
<span onclick="myFunc();" >
<img src="pic.jpg" style="cursor:pointer" />
if you click the image, or this text, the javascript function will be triggerd....
</span>

Maybe with jQuery ? Your HTML :
<img id="pic" src="pic.jpg" />
With this jQuery :
$('#pic').click(function() {
// Your stuff here
});
And this CSS :
#pic {
cursor: pointer;
}
Inline css and js are never the best way. :)

Use a class to identify your trigger object (be it an anchor or an image) and then perform click handling on that object:
Say the class name is "clickTrigger", then your HTML:
or
<img src="pic.jpg" />
or
<img style="cursor:pointer" class="clickTrigger" />
Then with javascript/jQuery attach to the click event:
Javascript:
var element = this.getElementsByClassName('clickTrigger')[0];
element.onclick = function (event) {
// handler
}
jQuery:
$('.clickTrigger').click(function (event) {
// Handler
});

Related

How to pass value of href to javascript and use it in window.location when a hyperlink is clicked?

I have two types of hyperlinks .When the first one is clicked the value of href is passed to function but its value never used in window.location!(Because it opens the link in safari instead of iphone webApp ).When the second hyperlink is called the value of href never get passed to function and again the href value is opened in safari instead of webApp!Could any one help me pass value of href to function and use it in window.location instead of opening it on safari.Thanks in advance.
<li class="x"><a id="1" title="1" href="./test.php?try" onclick="myFunction(location.href=this.href);"> <img id="Button1" src="./1.png" alt="" width="42" height="42" border="0"><div class="caption" style="color:red">FIRST</div></a></li>
<li class="x"><a id="2" title="2" href="./test.php" onclick="myFunction(location.href=this.href+'?try&appid='+currentID;return false;);"> <img id="Button2" src="./2.png" alt="" width="42" height="42" border="0"><div class="caption" style="color:red">SECOND</div></a></li>
<script>
function myFunction(myLink) {
alert("hello"+myLink);
window.location = myLink;
}
</script>
There are several things at play here. As fiprojects points out, it's best not to do inline JavaScript (some of the reasons are just personal preference). You'll end up repeating yourself and making it hard to maintain your code (among other reasons). Your best bet is to use Event Listeners (w3schools link, not always the best resource, but is sufficient for this example). These are extremely simple if you're using a JavaScript library (jQuery). But being that you requested a JavaScript solution, I'll outline how to do that in my answer.
First, let's format your code to make it easier to read:
<li class="x">
<a id="1" title="1" href="./test.php?try" class="myLink">
<img id="Button1" src="http://placehold.it/360x240">
<div class="caption" style="color:red">FIRST</div>
</a>
</li>
<li class="x">
<a id="2" title="2" href="./test.php" class="myLink">
<img id="Button2" src="http://placehold.it/360x240">
<div class="caption" style="color:red">SECOND</div>
</a>
</li>
I've only made a couple changes here. I removed the JavaScript onclick. I created a placeholder image (just for my own purposes, as I don't have your images, you'll want to put your images back in there). And lastly, I added a class="myLink" to your <a>. This will allow us to reference your links with our event listener a bit more easily.
For the JavaScript
<script>
var linksArray = document.getElementsByClassName("myLink");
var myFunction = function(event) {
event.preventDefault();
var href = this.getAttribute("href");
alert('hello ' + href);
window.location = link;
return false;
};
for (var i = 0; i < linksArray.length; i++) {
linksArray[i].addEventListener('click', myFunction, false);
}
</script>
The first line is creating an array with any elements that have class="myLink". We will loop through this array later, and add the event listener. Before we loop through, we need to create your function.
In order to prevent the default action that occurs when a user clicks the link, we need to stop propagation. So we'll use event.preventDefault() here. I have also added return false; to the function. Both are intended to do the same thing.
Instead of passing a variable, we'll use this to obtain the reference. We'll also use the JavaScript function getAttribute and pass href to it. This will pull the href value for you.
lastly, we are looping through our linksArray. We're adding a click event listener and assigning myFunction as a callback. Now, any time that a user clicks on one of the images, this function will fire off.
And here's a working example on JSFiddle.
You are trying to run before you can walk...
Your javascript needs alot more work. Avoid putting javascript inside html. Thus avoid things like:
onclick="myFunction(location.href=this.href);"
I would use jquery (javascript library) as it would help in the long run as it would lead you to be cross browser compatible.
Your "id" tags should be alphabetic or alphanumeric, not numeric. So id="1" is (I believe) illegal even if it works.
Actually... Sorry.... but the more i think about it, you really need a good book to advance your javascript before attempting what you want to do otherwise you'll fail to understand limitations or risks to some of your work.
Using jquery (which itself is written in javascript) you could change the URL via
$("#link1").click( Change1 );
$("#link2").click( Change2 );
function Change1()
{
$("#link1").href("./test.php?try");
}
function Change1()
{
$("#link2").href("./test.php?try");
}
The above would work if your id tags were renamed from id="1" to id="link1" and id="2" to id="link2"
Sorry I not help more than that...

Change image onmouseover

What's the correct way to change an image on mouseover and back on mouseout (with/without jQuery)?
<a href="#" id="name">
<img title="Hello" src="/ico/view.png" onmouseover="$(this).attr('src','/ico/view.hover.png')" />
</a>
Ok, this is working, but how to change back to the original image after mouseout?
If it is possible, I want to do this thing inline, without document.ready function.
here's a native javascript inline code to change image onmouseover & onmouseout:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png" onmouseover="this.src='/ico/view.hover.png'" onmouseout="this.src='/ico/view.png'" />
</a>
Try something like this:
HTML:
<img src='/folder/image1.jpg' id='imageid'/>
jQuery:
​
$('#imageid').hover(function() {
$(this).attr('src', '/folder/image2.jpg');
}, function() {
$(this).attr('src', '/folder/image1.jpg');
});
DEMO
EDIT: (After OP HTML posted)
HTML:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png"/>
</a>
jQuery:
$('#name img').hover(function() {
$(this).attr('src', '/ico/view1.png');
}, function() {
$(this).attr('src', '/ico/view.png');
});
DEMO
Thy to put a dot or two before the /
('src','./ico/view.hover.png')"
Here is an example:
HTML code:
<img id="myImg" src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"/>
JavaScript code:
$(document).ready(function() {
$( "#myImg" ).mouseover(function(){
$(this).attr("src", "http://www.jqueryui.com/images/logo.gif");
});
$( "#myImg" ).mouseout(function(){
$(this).attr("src", "http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif");
});
});
Edit: Sorry, your code was a bit strange. Now I understood what you were doing. ;)
The hover method is better, of course.
jQuery has .mouseover() and .html(). You can tie the mouseover event to a function:
Hides the current image.
Replaces the current html image with the one you want to toggle.
Shows the div that you hid.
The same thing can be done when you get the mouseover event indicating that the cursor is no longer hanging over the div.
You can do that just using CSS.
You'll need to place another tag inside the <a> and then you can change the CSS background-image attribute on a:hover.
i.e.
HTML:
<a href="#" id="name">
<span> </span>
</a>
CSS:
a#name span{
background-image:url(image/path);
}
a#name:hover span{
background-image:url(another/image/path);
}
<a href="" onMouseOver="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/ask-icon.png';" onMouseOut="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png';">
<img src="http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png" name="MyImage">
Demo
http://jsfiddle.net/W6zs5/
I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img, without "wrapping" it into the a tag (so instead of the document.MyImage, I used this.src)
<img
onMouseOver="this.src='ico/view.hover.png';"
onMouseOut="this.src='ico/view.png';"
src="ico/view.png" alt="hover effect" />
It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.

How do I fire a javascript playsound event onclick without sending the user to the top of the page?

I have the following code on a page on my site — when the user clicks on the image a sound plays:
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>
<span id="dummy"></span>
<div id="soundimage">
<img src="image.png" />
</div>
It all works great, but the image is at the bottom of the page, and when the user clicks the image they are redirected back to the top of the page. Is there any way to get this working so that there is only an audio change, and not a visual one (if that makes sense!)?
When using a mouseover function instead, such as
<a onmouseover="playSound('sound.mp3');"><img src="image.png" /></a>
the user remains where they were on the page, but I would like them to have the option of playing the sound on click and not on rollover.
The problem is your href attribute. # as an anchor sends it to the top of the page. Use
...
Also, always include an href attribute to links.
You can (and I think is more correct in cases where Javascript support is limited), to use a link like:
...
instead of Grexis one, because if the browser you're using doesn't support Js, then the "onclick" event will never be fired and thus Js won't be read. It won't be a problem, probably, but still you should consider using better coding techniques.
instead of having the onclick event in an a tag, get rid of it and put it on the img tag. if you like the cursor for links, you can change the style too.
Example code has been indented so it actually shows in the post.
<img src="image.png" style="cursor:pointer;" onclick="playSound ('sound.mp3')" />

html anchor tag reference

i have an anchor tag as below.
<a style="border:0px" href='javascript:deleteAttachment(this);' />
Inside the deleteAttachment, how can i get the anchor tag. Sending this to the method, sends the window element to the method.
function deleteAttachment(ancElement){
//Jquery operation on acnElement
}
Please helop me out.
I would recommend a slightly different approach, since what you're trying to do is a bit old.
assuming you already loaded jQuery, here we go:
<a id="myFirstLink" href="someHref" />
<a class="otherLinks" href="secondHref" />
<a class="otherLinks" href="thirdHref" />
<script>
$(function() {
$('#myFirstLink, .otherLinks').click( function(event) {
// stops the browser from following the link like it would normally would
event.preventDefault();
// do something with your href value for example
alert( $(this).attr('href') );
});
});
</script>
So basically what you can do is this: simply generate all your anchors like you would normally would and apply the same class name to each of them - in my example the class would be "otherLinks".
After that, all your links will be handled by that anonymous function.
Use the onclick handler:
<a onclick="deleteAttachment(this)">
or, the cleanest and most accepted method nowadays, have just the raw link in the HTML:
<a id="deleteAttachment">
and add the click event programmatically, in a separate script block, on DOM load:
document.getElementByID("deleteAttachment").onclick =
function() { ... you can use "this" here .... }
you must set its ID attribute
<a id="myAnchor" style="border:0px;" href="javascript:deleteAttachment('myAnchor');"/>
then use jquery to find it
function deleteAttachment(ID)
{
var MyAnchor = $('#'+ID);
}

Pull javascript code from tag using js or jQuery

How would I retrieve the javascript call in the anchor tag below in JS or JQuery? Basically I want to get the code ("javascript:do_my_function('blah', 'string1', 1);") retrieved so I can execute it. This anchor is embedded several deep in some div tags as well.
<a onmouseout="swapImage('btn1','','http://img2.comp.com/img/buttons/btn_g.png',1)" onmousedown="swapImage('btn1','','http://img2.comp.com/img/buttons/btn_g_d.png',1)" onmouseover="swapImage('btn1','','http://img2.comp.com/img/buttons/btn_g_a.png',1)" href="javascript:do_my_function('blah', 'string1', 1);">
<img id="btn1" width="180" height="60" alt="" src="http://img2.comp.com/img/buttons/btn_ge.png"/>
</a>
To retrieve it just use:
var href = document.getElementById('btn1').parentNode.href;
That just finds the img by id, and grabs its parent, the a tag in question.
To call it, you can use:
window.location = href;
Or you could parse it and eval() it. All of this is highly unconventional by the way. Do you not have any further control over the code?
To do it with jQuery you can do
var jscript = $('#btn1').parent().attr('href');
eval(jscript);
This is not a recommended way to do things. Changing the html would be much better

Categories

Resources