Jquery onclick event - javascript

I have a link
<a id="special_link" href="" onclick="" >Link</a>
Is it possible to use Jquery in the onclick part and apply something to the current element?
Something similar with :
$("#special_link").html('test');
Update :
I want to change the content after click
I would prefer using $this so I don't depend on the id

Yes, it's possible:
<a href='whatever' onclick='$("#special_link").html("test");'>blah</a>
It's rarely necessary, though. Usually you can hook these things up later, using a selector that finds the a element and uses bind or click to hook up a handler, e.g.:
jQuery(function($) { // Function gets run at DOM load time
$("some_CSS_selector_that_finds_the_a_element").click(function() {
$("#special_link").html("test");
return false; // Do this only if you don't want the link followed (which I'm guessing you don't)
});
});
If special_link is the id of the link you want to do this on (I wasn't sure, from your question), you can simplify that:
jQuery(function($) { // Function gets run at DOM load time
$("#special_link").click(function() {
$(this).html("test");
return false; // Do this only if you don't want the link followed (which I'm guessing you don't)
});
});
More:
bind
click
$

The code you provided will work as-is in the onclick attribute, like T.J. Crowder pointed out. Is your problem using jQuery for the current element? like this:
<a href='#' onclick='$(this).html("a test link");'>a link</a>

You can refer to the current element as this.
Example:
<script ...>
$("#special_link").click(function() {
console.log(this) // You'll see the HTML element, not wrapped by jQuery
$(this).html("Bar");
})
</script>
Foo
Please, don't use onclick, rely on bind that's more generic and unobstructive.
Good luck!

If you want it inline, and it's as simple as changing the HTML, I probably wouldn't use jQuery for it.
<a id="special_link" href="#" onclick='this.innerHTML="some new value";'>click me</a>
Example: http://jsfiddle.net/8ucGB/2/

Related

How to use functions on href (html/js)

want to build a function inside a href link.
should look like this
How do i complete it correct?
Use onclick to trigger a function instead of href
HTML
JS
function destroy()
{ //rest of the code
return false; // return false is use to prevent default behavior
}
Note: If you dont use return false or event.preventDefault it will execute the default behavior
There are different option for you to use.
Most of them already answered in another question.
Sum it up:
You can do it like this (the correct way):
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="destroy();return false;">link text</a>
What it means is that after the destroy function is called it wont direct the user to the link provided. Alternatively you can use jQuery to make a listener on the specific a href like this:
$('#myLink').click(function(){
MyFunction();
return false;
});
The rest can be read on the provided link :)

How can I pass an object value name to a function in Jquery

I'm working with the JQuery Simple modal plugin and I would like to pass a Freemarker variable/object on the click of a link to my Jquery function.
As a test, I created an alert box to see if the value is being passed and it doesn't seem to work.
$(function() {
// Load dialog on page load
//$('#basic-modal-content').modal();
// Load dialog on click
$('#hey').click(function myName(uid) {
var x = uid;
alert(uid);
return false;
});
});
HTML
<div id="disclaimer${item.uid}">
Modal data
</div>
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
The alert box just comes up as a blank object. Any help would be appreciated. Thanks!
First off, you look like you are confusing the html onclick attribute with the jquery .click method.
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
This will call a javascript function named "myName" and pass it a the string ${item.uid}. Note, this is a string because you wrapped it in single quotes. If you do an alert, your alert will literally say "${item.uid}".
Then you have a jquery bind event for click:
$('#hey').click({....
Ok, you need to pick one. Either use the onclick to call a javascript function or use the bind click event. Both methods can work (I prefer javascript onclick functions myself but that is just opinion).
If you want to use the jQuery bind, put a debugger; line in it so that you can step through it easily and watch. I typically use e for my event variable and e.target gets the target of the event. It will look something like this:
$('#hey').click(function(e){
debugger;
alert($(e.target).attr('data-uid'));
});
--- edit---
Adding my note below here so it is easier to read.
One thing I like to do in my onclick functions is to pass the this pointer. This is especially useful if you have multiple of the same kind of node that are calling the same function.
<a onclick="myName(this)" id="hey2">Read the blog</a>
<a onclick="myName(this)" id="hey3">Read the blog</a>
then, in the javascript you function looks like:
function myName(ptr)
{
$(ptr).....
// do some stuff
}
try using this:
function myName(uid){
alert(uid);
}
You dont need to wrap it in a jquery event handler, because you are already calling it as an onclick event from your Freemarker template.
Alternatively, you could do something like this:
<a data-uid="${item.uid}" id="hey">...</a>
And have your javascript like this:
$('#hey').click(function(){
alert($(this).data('uid'));
}

run a function when a user clicks on any list element

This is probably a very common question, but I was unable to find an answer myself;
All my list elements call the function setQuery like this
onClick="admin_stats.setQuery(this);"
rather than [hardcode] add this to every list element, is there a way to simply have it run when a list element is clicked?
I'm not very familiar with jQuery Live or binding/unbinding, but I think they would play a role here?
Before I reinvent a rather square-looking wheel I thought I might ask =)
edit: my list elements look like
<ul>
<li id="usersPerMonth" onClick="admin_stats.setQuery(this);">Users per Month</li>
<li id="statsByUser" onClick="admin_stats.setQuery(this);">Stats by User</li>
</ul>
the this.attr("id") is then used to look up what the actually SQL text looks like, from a json-style variable:
queries : {
usersPerMonth : " ... some sql ...",
statsByUser : " ... some sql ...",
...
}
so that's why I have the divs named that way (and I'm open to design suggestions)
$(function() {
$('#myList').delegate('li', 'click', function() {
admin_stats.setQuery( this );
});
});
This assumes your <ul> element has the ID myList. It will handle clicks inside of it on any <li> elements, calling your function, and passing this as the argument.
The .delegate() code is wrapped in $(function() {}); so that it doesn't run until the DOM is ready. This is a shortcut for jQuery's .ready() function.
Yes - use jQuery like this:
$('li').live("click", function(event){
admin_stats.setQuery(event.target);
});
This is assuming you want to set it to every li element. You can find the documentation for live here: http://api.jquery.com/live/
What live does makes sure that all elements passed to it will always have the click handler in the function specified.
jQuery is probably your best bet. Are you adding new elements on the fly, or will the elements be there when the attach is ready to go? If they're "satic" in the sense that once the page is loaded that's it, you could use:
$(document).ready(function(){
$('li').bind('click',function(e){ // may need to change the selector to be more specific
admin_stats.setQuery(this);
});
});
that needs to fire onClick... so:
$('li').click(function(){
admin_stats.setQuery($(this));
});
In jQuery you select elements using CSS-style selectors (can use this if more elements will not be added; this uses .click()):
$(function() {
$('#liContainer li').click(function() {
admin_stats.setQuery(this);
});
});
We put the whole thing inside $(function() { ... }); because the page needs to be ready before binding the event handler. Alternatively, you could do it like this if more elements are added. This uses .delegate():
$(function() {
$('#liContainer').delegate('li', 'click', function() {
admin_stats.setQuery(this);
});
});

How do you override inline onclick event?

This seems deceptively simple.
How do you override the onclick event in the following HTML using JavaScript?
<a id="sample" href="..." onclick="alert('hello world')" />...</a>
I've tried it with jQuery, but that didn't do the trick:
$('#sample').attr('onclick','alert("done")')
Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.
Try this:
// Setting the DOM element's onclick to null removes
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });
This can also be done without jQuery:
document.getElementById("sample").setAttribute('onclick','alert("done")');
<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>
Or
$('#sample').attr('onclick','alert("done"); return false;')
Despite being able to set the return false; either directly in the onclick or by using jQuery, it doesn't actually require jQuery to be used at all. The benefit is if for whatever reason your jQuery script leads to a 404, your code will still work.
I found the answer here.
Try:
document.getElementById("sample").onclick = $.noop;
$.noop == function(){};
jQuery noop

referencing (this) in a function

I have elements being generated by dynamic html, I would like to reference the particular href that is calling the function when one of many may be calling it.
Link
Does not work when I try to reference $(this). Is there another way to do this or do I have to make dynamic ids?
Link will work if you want to pass the href.
However, onsomething handlers in the html code are not jqueryish at all.
Give your links a class and setup a live handler:
$('.mylink').live('click', function() {
// do whatever you want with this or $(this) or this.href or $(this).attr('href')
});
putting the js parts in the href attribute is a bad idea. best practice is adding a handler with addEventListener but here you can get away with setting onclick directly.
Link
and your function would be like
function Foo(e) {
var a = e.target || e.srcElement;
// TODO: stuff
if (e.preventDefault) {
e.preventDefault();
}
else {
return false;
}
}
so when you click the link, Foo is called with the event as a paremeter. the event object has a reference to the source element, either as target in standards browsers or srcElement in IE. the preventDefault/return false; combo at the end prevents the browser from "following" the link to #.
edit: on second thought, since you have many links, using jquery to add handlers the recommended way is probably better (although the first solution is still fine).
...
<a id="A5" href="#" >Link</a>
<a id="A6" href="#" >Link</a>
<a id="A7" href="#" >Link</a>
...
<script>
$('a').click(Foo);
</script>
No point in using the javascript: pseudo protocol handler.
Use
Link
instead.

Categories

Resources