Reading the IMG within an A on click jQuery - javascript

I'm trying to adapt my script to read the alt attribute of an img within an a.
For some reason, this isn't work:
$("#thumbs a").click(function(event) {
event.preventDefault();
var title = $(this + " img").attr("alt");
alert(title);
});
It returns a value of [object Object].
I'd appreciate some help, thanks.

You need to change your selector to use the second parameter, which is the context in which to evaluate the selector.
$("#thumbs a").click(function(event) {
var title = $('img', $(this)).attr("alt");
alert(title);
});
Working example: http://jsfiddle.net/q4Bsq/2/

$(this + " img") will not select anything so the alert which you are seeing is just an empty jQuery object. You should using $(this).find("img") which will select all the img elements within this i.e the anchor element in this case.
$("#thumbs a").click(function(event) {
event.preventDefault();
var title = $(this).find("img").attr("alt");
alert(title);
});

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");
});

How to get hash from document url

if I use:
jQuery(document).ready(function() {
console.log($(this));
});
then in console I have object:
[Document mypage.html#weather]
how can i get for this last ID? In this example this is #weather. I would like use alert #weather in selector, for example $(data_from_console + '.add').val();
Do you want to get the last element that has an ID attribute?
If so:
$(document).ready(function () {
console.log($('body *[id]').eq(-1));
});
EDIT
On a closer look, are you looking for the hash tag? ie. if your URL is mypage.html#weather you want the #weather ?
In that case try:
$(document).ready(function () {
console.log(document.location.hash);
});
You can use last() method. Try this:
$(document).ready(function() {
$('body *').each(function() { //selects all elements in body which got id
var lastEle = $(this).last(); //selects last one of them
console.log(lastEle.attr('id'));//returns it's id to console log
});
});

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