Getting href value via jQuery - javascript

I want to get the value of href and hash of an a tag. When I do
$(document.body).on('click',"a",function(event){
console.log($(this));
});
I see an object with something like
[a.internalLink, context: a.internalLink, jquery: "1.10.2", constructor: function, init: function, selector: ""…]
0: a.internalLink
accessKey: ""
attributes: NamedNodeMap
...
hash: "#abc.1.2"
...
href: "http://www.example.com/page.html#abc.1.2
...
But when I tried to get the value by console.log($(this).href), it just doesn't work (prints out "undefined"). How can I get it?

If you want to refer to specific attributes of an element, you can use the attr function of jQuery:
$(document.body).on('click',"a",function(event){
console.log( $(this).attr("href") );
});

$( "a" )[0].href or $( "a" ).attr( "href" ).

$('body').on('click', 'a', function () {
console.log($(this).attr('href'));
});

$(document.body).on('click',"a",function(event){
console.log($(this).attr('href'));
event.preventDefault();
});

As per your code clicking "a" tag will give list of all the anchor tag objects in your page in an array for $(this). And each of these objects have jQuery specific properties (as this wrapped in jQuery) like href, hash etc.
So if you have only one anchor tag then you can use $(this)[0].href
But the more specific solution will be to use $(this).attr("href")

You can get both: full href or just the hash using this code:
$("body").on("click","a",function() {
var href = $(this).attr("href")
var hash = href.replace(/^.*?#/,'');
console.log(href + " - " + hash);
});
you can see a demo on JSFiddle.

Related

Append input box with JQuery

I was trying to add text into field with id #shouttext, but i need to trim value from onclick event which is just after (' and also delete ') symbols.
So if i have
<img src="images/smilies/at.png" alt="" title="" class="smilie smilie_9 smilie_pointer" onclick="MyBBEditor.insertText(':at:');">
I want to get
:at:
and add it to input with #shouttext id. Below is my code, which doesn't work - and i think its blocked by defined onclick value, which i was trying to remove.
<script type="text/javascript">
$( document ).ready(function() {
$('.smilie').click(function()
{
var s1,s1;
s1=attr("onclick");
s1=s1.replace('MyBBEditor.insertText(\'', '');
s2=s1.replace('\')', '');
$('.smilie').attr('onclick','').unbind('click')
$('#shouttext').val($('#shouttext').val()+s2);
})
});
</script>
Thanks for any help in advance!
you could try also:
var str = $(".smilie").attr("onclick").split("'")[1];
to get the :at: try it here: fiddle
now you can use it here:
$('.smilie').unbind("click");
$('.smilie').click(function() {
var str = $(".smilie").attr("onclick").split("'")[1];
$('#shouttext').val($('#shouttext').val() + "" + str);
});
or how #eg_dac says, you can override the click event with $.on()
instead of unbinding it in the click, you can do
$(".smilie").attr("onclick", ""); // clear the already declared attribute.
$(".smilie").on("click", function(){
$('#shouttext').val($('#shouttext').val()+s2);
});
Example found here http://jsfiddle.net/meougz1L/
$("img").attr("onclick","");
$("img").on("click", function(){
alert("click event overridden");
});

Listen to objects click

I'm trying to listen to both "button" and "a" click, and then pass the value of the attribute "name" to a variable, I can't find what's wrong with my code:
$('a').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});
$('button').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});
Update: I have a PHP script that do something different according to the "linkPressed" value. Seemingly, this code is applicable also for <a> and <button> that don't have "name" attribute, which ruins my script. Is there a way to exclude the objects that don't have "name" attribute from the "click listener"?
To only select elements that have an attribute name, use the attribute selector:
$('a[name], button[name]').click(...);
// or
$('a, button').filter('[name]').click(...);
You can separate your selectors using comma ,. It's probably not working because you've initialize anchor variable two times:
$('a, button').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});
You can bind the handler only to elements with name attributes:
$('a[name], button[name]').click(function() {
$('#linkPressed').val(this.name);
}
use multiple selector by the , at a one time it remove repetitive code
may be #linkPressed is a tag type not a input type at that time use text() at the palace of val()
$('a,button').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});
I think this is it.
$("a, button").click(function() {
var anchor;
if($(this).attr("name") != undefined) {
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
}
});

Making link to go somewhere else than its default href

I want to grab the link text and append it to the URL and open the new URL with querystring added Onclick of the Original Link..How do I get the link text using javascript or jquery?
<a href="www.mysite.com/search.aspx?kwd=" onClick="location.href='http://mysite.com/search.aspx?kwd='+ Grab text 'kangaroo' and append here as QueryString>Kangaroo</a>
You can access the current anchor through this. The text can be then had through this.innerHTML.
Something like this...
Kangaroo
$('.your-url').click(function(event) {
event.preventDefault();
window.location= $(this).attr('href') + encodeURIComponent($(this).text());
});
I noticed that none of the other answers were encoding the text in the link to be a query-string parameter.
Inline (like your example) would look like this:
Kangaroo
return false should be unnecessary because once you change the location object scripts stop running and the page changes.
UPDATE
You can use $.trim() to:
Remove the whitespace from the beginning and end of a string.
Source: http://api.jquery.com/jquery.trim/
$('a.your-url').click(function(e) {
e.preventDefault();
url = $(this).attr('href') + $(this).text();
location.href = url;
});
To send the page to the link's href + text when clicked, this should work:
$("a").click(function(){
location.href = $(this).attr("href") + $(this).text();
return false;
});
But why not just set the hrefs correctly when the page loads, and get rid of all these onclick handlers altogether?
$("a").each(function(i, el) {
var $el = $(el);
$el.attr("href", $el.attr("href") + encodeURI($el.text()));
});
jQuery example:
$('a.link').click(function () {
var $this = $(this),
href = $this.attr('href');
window.location = href + encodeURIComponent($this.text());
event.preventDefault();
return false;
});
Demo

Identify the a tag

Need to identify each of these 'a' tag in div and bind an onclick event.I have binded the same.I need to append some text below the clicked 'a' tag.But when i tried with my code it binds to all the 'a' tag in the div.How can i specify the 'a' tag which i have clicked.I can make changes to the content in div using jquery.can't modify the content in 'a' tag.
<div class="people_rt_link2">
2011<br><br>
2008<br><br>
</div>
$(document).ready(function() {
var timesClicked = 0;
$('.people_rt_link2 a').bind('click', function() {
jQuery.post("<?php bloginfo('template_directory'); ?>/test.php", data, function(response) {
alert('Got this from the server: ' + response);
//this response should to binded to the clicked a tag
//$(this).after('<div>'+response+'</div>');
});
timesClicked++;
if (timesClicked >= 1) {
$(this).unbind();
}
});
});
Use this to refer to the clicked <a>. Example using jQuery:
$('div.people_rt_link2 a').click(function(){
$(this).unbind('click');
var that = this;
$.post('somepage.php', function(data){
$(that).after(data);
});
return false;
});
Example
Let me know if that's not exactly what you were trying to achieve.
Theres lots of ways to specify the a tag you want to append text too.. first child.. first of type.. but mostly you just append an id to the tag and let javascript handle it..
$("people_rt_link2 a.YourClass").bind("click", function({do stuff}));
http://www.w3schools.com/tags/tag_a.asp
try something like this:
$("people_rt_link2 a").bind("click", foo(<!--Put here all your code you want to be executed -->));

Javascript , jQuery - what have I done wrong?

$(document).ready(function () {
$("href").attr('href', 'title');
});
$('a[href$=.jpg]').each(function () {
var imageSrc = $(this).attr('href');
var img = $('<img />').attr('src', imageSrc).css('max-width', '300px').css('max-height', '200px').css('marginBottom', '10px').css('marginTop', '10px').attr('rel', 'lightbox');
$(this).replaceWith(img);
});
});
This is the jQuery code I have at the moment, which I want to change all links' href to the same as their title, before then embedding them in the page. Yet with the changing href to title bit in the code, it stops working. I'm new to Javascript so am definitely doing something wrong, just not sure what yet! Any help much appreciated!
Thank you guys
EDIT
This is the html that I want to change:
<p class="entry-content">Some interesting contenthttp://example.com/index.php/attachment/11</p>
You are changing it wrong, you are trying to select href elements instead of a.
This fix should do it:
$("a[title]").each(function() {
$(this).attr('href',$(this).attr('title'));
});
It will select all a elements with title and set the href with this value.
Here's a much more efficient way.
Since you're just replacing the <a> elements, there's really no need to change its href. Just select the <a> elements that end with jpg/jpeg, and use that attribute directly.
Example: http://jsfiddle.net/5ZBVf/4/
$(document).ready(function() {
$("a[title$=.jpg],[title$=.jpeg]").replaceWith(function() {
return $('<img />', {src:this.title, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});​
Your .each() is outside the .ready() function.
You can accomplish the href change easily like this:
$(document).ready(function () {
$("a").attr('href', function() { return this.title; });
});
The .attr() method will accept a function where the return value is the new value of (in this case) href.
So the whole thing could look like this:
Example: http://jsfiddle.net/5ZBVf/3/
$(document).ready(function() {
$("a[title]").attr('href', function() { return this.title; })
.filter('[href$=.jpg],[href$=.jpeg]')
.replaceWith(function() {
return $('<img />', {src:this.href, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});
This line:
$("href").attr('href','title');
Is finding all href elements and replacing their href attr with the string 'title'. Since there is no such thing as an href element, Try this instead:
// for every anchor element on the page, replace it's href attribute with it's title attribute
$('a').each(function() {
$(this).attr('href', $(this).attr('title');
});
Check this out: http://jsfiddle.net/TbMzD/ Seems to do what you want.
Note: $(document).ready() is commented because of jsfiddle, you actually need it in your code.
Try:
$("a").each(function () {
var $this = $(this);
$this.attr('href', $this.attr('title'));
});

Categories