call javascript function on hyperlink click - javascript

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?

Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.

The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link

With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>

The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>

I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>

Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.

Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.

If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>

Related

Basic jQuery Issues on IE9 (Toggle)

I'm not really a developper. I prefer to design my websites ... So, for my actual project, i must developping some "basic" scripts.
I've met a problem with this:
<script type="text/javascript">
$("button").click(function toggleDiv(divId) {
$("#"+divId).toggle();
});
;
</script>
Into Head-/Head
LINK
<div> id="myContent">Lorem Ipsum</div>
It works for IE8. (Miracle). But not the others browsers...
The idea is that when u click on "LINK" a windows appears and when you click again, the window close.
Any idea ?
Thanks for u time !
One of the problems is you're mixing two different styles of binding event handlers: one of them is good (the jQuery method), the other is bad (the javascript: protocol in your href attribute) - the two don't work together in any way. Another problem is that your selector is completely incorrect (it's looking for a button) for the HTML you've provided (you never create a button).
I'd suggest using a HTML5 data-* attribute to specify the id for the <div> on your <a> element:
LINK
<div id="mycontent">Lorem ipsum</div>
Then use the following jQuery code:
$('a').click(function(e) {
e.preventDefault(); // e refers to the event (the click),
// calling preventDefault() will stop you following the link
var divId = $(this).data('divid');
$('#' + divId).toggle();
});
Note that I've used this in the above code; what this refers to depends on the context in which you use it, but in the context of a jQuery event handler callback function, it will always refer to the element that triggered the event (in this case, your <a> element).
If you extract toggleDiv from the handler, it ought to work. You will probably also need to return false to keep the href from trying to go anywhere.
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
return false;
}
</script>

Dijit ComboButton / DropDownMenu onclick misunderstanding

I've just begun to play around with Dojo. I simply wanted to display a dialog when an item in a Dijit ComboButton's DropDownMenu is clicked. I tried using dojo.connect to associate the onclick event with a function which would simply display a dialog with the text contained in the item, with no luck.
I've managed to get it working in a horrible way. All the work is now actually written to the onclick attribute manually. I'm clearly misunderstanding something here. This is what I currently have:
JS:
require(["dijit/form/Button", "dijit/form/FilteringSelect", "dijit/DropDownMenu", "dijit/MenuItem"]);
//if the following is defined inside dojo.ready, nothing happens
function getmail(text)
{
alert('No mail from '+text);
}
dojo.ready(function(){
//the following does nothing:
dojo.connect(dojo.query(".dijitMenuItemLabel"), "onclick", function(evt) {
console.log("mail item clicked");
alert('Blah');
//dojo.stopEvent(evt);
});
});
HTML:
<form method="POST">
<div data-dojo-type="dijit.form.ComboButton" id="getmail">
<span>Get All Mail</span>
<div data-dojo-type="dijit.DropDownMenu">
<div data-dojo-type="dijit.MenuItem"
data-dojo-props="onClick:function(){getmail(dojo.trim(dojo.query('.dijitMenuItemLabel', this.domNode)[0].innerHTML))}">
Yahoo</div>
<div data-dojo-type="dijit.MenuItem">Google</div>
</div>
</div>
</form>
What does it look like I am clearly misunderstanding about Dojo?
(Or maybe I'm making simple JavaScript mistakes)
JSFiddle
You should be able to do it with something like
var myButton = dijit.byId('getmail');
myButton.on('click', function(){ alert('clicked') });
My guess is that you confused dojo.byId and dijit.byId when you fetched your button - regular DOM nodes work when you conenct a lowercase 'onclick' but widgets fire a camel case 'onClick' event (the distinction is because dijits fire with some keyboard events, for accessibility).
However, for newer versions of Dojo it is probably best to stay away from dojo.connect and instead just use simpler ".on" API I showed.
Ah, and before I forget, it also looks like you could have forgotten to run the Dojo parser (or set parseOnLoad to true) so the button was never created. Can you provide a fully executable example on JSFiddle?

javascript de-anonymizing a click function

really basic stuff here. I'd like to give a click function a name and assign some parameters to it. The goal is code reusability such that I can write only one generic function for common tasks such as for enabling users to delete various data.
Here's a jsfiddle to show you what I mean.
And here's that code:
the HTML:
<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>
and the JS:
// this function would be loaded on my site's template and therefore would be available across my entire site.
function deleteThis(data_id){
$('button').on('click', 'button', function(){
$('div[data-id="'+data_id+'"]').hide();
});
}
var clicked_id=3;
function deleteThis(clicked_id);
// this function would be called on the various pages where users can delete things and this variable, clicked_id, would be assigned=3 by the user's action on that page.
How do I give this button click event a name?
update thanks all! the $('button') should have been $(document.body) or the button's parent element. It works if you make that simple change. You can also do it as Michael Buen suggests below.
Just refactor your code, put the delete functionality on its own function
<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>
​
$('button').on('click', function() { deleteImmediately(3) });
function deleteImmediately(id) { -- refactored code
$('div[data-id='+id+']').hide();
}​
Live test: http://jsfiddle.net/e2kuj/2/
In your fiddler, the (function deleteThis(){})() is making it private and you are trying to access it as a global!
I think you're misunderstanding events. deleteThis only makes sense if it's in the handler.
corrected HTML: (don't use custom attributes for referencing HTML - They're slower)
<button>delete this</button>
<div id="del_3" class="delete">something bad</div>
<div id="del_4" class="delete">something else bad</div>
JS: (untested)
var deleteTargetId = 'del_3'; //clicked_id renamed for clarity
function deleteThis(targetId){
$('#'+targetId).remove(); //removes rather than hides the html
}
$('button').click( function(){
deleteThis(deleteTargetId);
} );
Now you could swap deleteTarget and the HTML with that ID would get yoinked.
However, if this is homework, I'm wondering if you understand the assignment. The var named 'clicked_id' suggests the idea is to click the divs to make them disappear and use delegation. That one's easy.
You'll need to understand event delegation and event bubbling to see what's going on here. Basically when something is clicked, the event then fires on the parent element and then that parent element's parent element, all the way up to the HTML tag. This happens with all events and doesn't cause the trouble you might think because containers are rarely assigned listeners for events. Links and buttons are more typically end point nodes or at most contain a span or an image. Usually when bubbling causes a problem it's because somebody's doing something awful with HTML or they should've been using delegation in the first place.
'on' is the new piss-poor name for the once appropriately named and less confusion-prone 'delegate' jquery method. Essentially anything in the body with the class 'delete' triggers the handler. We don't care about the ID since the idea is to kill the div that was clicked and 'this' gives us a reference to it. This is unusual behavior for JQ, since most methods would have 'this' point at the 'body' but it's obviously a more useful thing to point at for event delegation.
$('body').on('click', '.delete', function(e){
$(this).remove(); //this refers to the originally clicked element
} );
//note: not the solution you asked for, but possibly the one you needed.
It was almost right. I updated it -> http://jsfiddle.net/fz5ZT/41/
function deleteThis(id){
$('button').click(function(){
$('div[data-id="'+id+'"]').hide();
});
};
deleteThis(3);​
you can remove the element in a different way:
$('button').on('click', function(){
$(this).next("div").remove();
});
http://jsfiddle.net/fz5ZT/46/
You could just use $('button').on('click', 'button', clickHandler); to reference the clickHandler function.
I am big fan of such things since apart from being reusable it has the following advantages.
I will be able to just send across a patch in case there's a bug in the clickHandler
Someone can augment my method which is not possible with anonymous methods
Readable, and also useful to see the stack trace in case of errors
Hope that helps.
Update:
function clickHandler(ev) {
ev.preventDefault();
// ... handler code
}

How to make an <a> tag element to trigger multiple functions with javascript/jquery

There is a link in my webpage, the link itself triggers a function that I could not modify, but I want to make the link, when clicked, also calls another JavaScript function at the same time or preferably after the first function is done. So one click to call two functions...could it be implemented? Thanks
<a title="Next Page" href="javascript:__doPostBack('Booklet1','V4504')">Next</a>
is the sample tag I want to modify, how could make it also call "myFunc" at the same time or preferably after _doPostBack is done.
P.S. the function parameter for _doPostBack such as V4504 is dynamically generated by the ASP user control. So I cannot simply treat it as a static function and bind it with another. I think I could only append some function to it? Unless I parse the whole page first and extract the function name with its current parameters...Since every time I click the link, the parameter such as V4504 changes its value....
Thanks!
You should be able to attach multiple event handlers to a single anchor tag, either with .onclick or .addEventListener('click', function)
https://developer.mozilla.org/en/DOM/element.addEventListener
You can attach a handler to an element click event using plain Javascript in such a way:
function hello()
{
alert("Hello!")
}
var element = document.getElementById("YourAElementID");
if (element.addEventListener)
{
element.addEventListener("click", hello, false);
}
else
{
element.attachEvent("onclick", hello);
}
It supprots all common browsers.
Yes, you can do this MANY ways (I use both $(this) and $('identifier') as you don't say how the functions are bound) :
$(this).click(function(){
my_function_1();
my_function2()
});
Or
$('my element').click(function(){
my_function_1();
});
$('my element').click(function(){
my_function_2();
});
Or, if the functions reside on another object:
$(this).click(function(){
my_function_1();
$('#other_element_id').trigger('click'); //there are a bunch of syntaxes for this
});
Sans JQuery, you can use:
var myObj = document.getElementById('element name');
myObj.addEventListener('click', function(){
alert('first!');
});
myObj.addEventListener('click', function(){
alert('second!');
});
Clicking will result in two sequential alert prompts

adding a mouseover to a link through javascript

Simple quick question....
I have the following link html:
<a href="http://www.site.com/" onmouseover="" />
I have a javascript function which I want to enter some onmouseover information into that link dynamically. So, lets say it then becomes this for example if this javascript function is called:
<a href="http://www.site.com/" onmouseover="alert('howdy')" />
any ideas how to do this?
Add name attribute to and assign onmouseover
<a href="http://www.site.com/" onmouseover="" name="xxx"/>
document.getelementsbyname('xxx').onmouseover = function() { alert('howdy') }
Answer was, using setAttribute() javascript.
I think you want to say: dynamically change your href attribute information then you can do it by jquery
//Write code for prompt box and get value (when mouse-over)
$("a[href='http://www.google.com/']").attr('href', 'YOUR_GET_VALUE')
If you can use jquery, see: http://api.jquery.com/hover/
This is better than changing the attribute directly. Your javascript function can dynamically bind/unbind the mouse hover event and execute your alert call.
Otherwise your javascript function will need to dynamically change the attribute but you'll need to work around browser differences to locate the correct element then locate and modify the onmouseover attribute.
two options:
if it's something small:
<a href="http://www.site.com/" onmouseover="this.href = 'http://stackoverflow.com'" />
if you have something more to do:
<script type="text/javascript">
function doSomething(elem) {
elem.href = 'http://stackoverflow.com';
}
</script>
test
Or as stated before: use jQuery or any other framework to make your life a lot easier
The following works for jQuery every time
first the javascript:
$(document).on('mouseenter','.hovLink', function (e) {
e.preventDefault();
e.stopPropagation();
alert('entering ' + e.target.id);
}).on('mouseleave','.hovLink', function (e) {
alert('exiting ' + e.target.id);
});
and here is the HTML
Link

Categories