referencing (this) in a function - javascript

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.

Related

How to retrieve information from an element in Javascript when onclick is triggered

Let's say I have a link in my DOM (but any element would be accepted), with a call to a Javascript function :
<a href="google.com" onclick="myFunction()">
, and a Jquery function to replace the click on that link and retrieve its href attribute (sorry, I'm working in Jquery, but feel free to answer in vanilla JS) :
function myFunction() {
$(this).click(function() { return false; }); // Cancel normal behavior.
console.log($(this).attr("href"));
}
This actually doesn't work. Usually, we need to point to an element's ID or Class to get its informations ; but if we can't set an ID or Class or anything and just process some links in a page, how to directly retrieve their informations ?
The title of this topic is intentionally general, because the method should be working for any HTML element.
yes you are right that with id or css selector you could do. But there is another way.
Just pass this while calling function and then you can access all attributes of the element like below :
<a href="google.com" style="background-color: yellow" onclick="myFunction(this, event)"> click me !!!! <a>
then you can access all info like below :
function myFunction(element, event) {
event.preventDefault(); // event object can be passed
element.style.backgroundColor = "red" // attribute can be accessed
console.log(element.attributes["data-name"])
}
You can access clicked element as below
<a href="https://google.com" onclick="myFunction(this)">
function myFunction(that) {
console.log(that.href);
}
HTML click
JS
function myFunction(event) {
event.preventDefault();
// Do your stuff with event.target which is <a>
}

Good way to keep an anchor tag without default url

In our page we have a slew of anchor tags to which we dynamically attach click handlers. In such a case what is the best way to keep an anchor tag in the mark up?
Currently we have
<a href="javascript:void(0);" >....</a>
We need void value for href as some of them may not get attached with click handlers.
Ommit the href-attribute and when assigning the onclick also set the cursor-style of the elements to "pointer" , otherwise users with JS disabled will be confused when clicking on the elements and nothing happens.
Returning false from a jQuery event handler will prevent the default behavior (and bubbling) for you. There's no need to mess with the href attribute (though that won't hurt).
$(document).on("click", "a.yourSelector", function(){
//your code
return false;
});
Or of course jQuery pre 1.7
$(document).delegate("a.yourSelector", "click", function(){
//your code
return false;
});
For more information on cancelling dom events, see this question (and answer) and this link
The simpler code would be like this:
<a href='#' class='do-stuff'>Link</a>
The "#" sign keeps the html code clean, and readable
jQuery(document).ready(function() {
jQuery(".do-stuff").click(function() {
alert("clicked");
return false; // disables default link action
});
});

Jquery onclick event

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/

Reassign onclick for anchor tag

I have a problem with <a> tags.
I need to reassign an onclick event to this tag, but the href attribute must contain a link.
For example, I have some link:
Wikipedia
And i need to change only the onclick event for this link so that when I click on it, some JavaScript function is called.
Don't forget to return false in 'onclick', or browser will handle click and open link in href.
<a href="http://en.wikipedia.org" onclick="yourfunction(this); return false;" >Wikipedia</a>
Not sure what you mean, but try this:
$(function() {
// Find all links pointing to wikipedia
$("a[href*='wikipedia.org']").click(function() {
// Do something
return false; // to prevent the link from actually going to wikipedia
});
});
but href attribute must contain a link
If you provide a link then the page will be redirected there, so you might want to do this:
Wikipedia
This makes sure that you perform your functions first and finally redirect function to redirect the page to the url you specify.
The simplest way would be to give your link an id, ie
Whatever
Then simply assign an onclick via jquery like so:
$("a#myLink").click(function() {
//Go wild!
});

jQuery DIV click, with anchors

To make click-able divs, I do:
<div class="clickable" url="http://google.com">
blah blah
</div>
and then
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
});
I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div contains a click-able element, such as
<a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called
This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div.
Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
return false;
});
See event.preventDefault() vs. return false for details on return false vs. preventDefault.
$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) {
event.preventDefault();
$('div.link1').show();
//whatever else you want to do
});
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) {
event.preventDefault();
window.location = $(this).attr("url");
});
<div class="info">
<h2>Takvim</h2>
Click Me !
</div>
$(document).delegate("div.info", "click", function() {
window.location = $(this).find("a").attr("href");
});

Categories

Resources