I have got this html:
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
I am trying to get this:
$('body').on('click','.hostPic',function(){
console.log($(this).attr('data-name'));
});
Whenever the picture is pressed, I want to gets its data-name attribute, but it doesnt work.. I get undefined reported when I try to retrieve the attribute. Any reason why?
Add the hostPic class to that image.
Additionally, you can just use .data('name'), but it doesn't actually make a difference. Older browser may have trouble with .data, but it's never been a problem for me.
$('.hostPic').click(function() {
console.log($(this).data('name'));
}
Make sure your image has the class 'hostPic' and then do the following in your jQuery:-
$('.hostPic').on('click', function() {
console.log($(this).data('name'));
}
The following code worked for me, maybe you are attaching the events wrong object, you can understand that by debugging the this object instead of data-name.
And another thing is if you are going to use .data just for read string you should use .attr as the .data caches and tries to convert the value its appropriate type like number or JSON it is a heavier process than .attr.
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
$("img").click(function () { alert($(this).attr("data-name")); });
Related
I'm doing kinda learning by doing JavaScript right know, but I have a problem, where I can not find the solution on stackoverflow. I want to replace a String on a webpage, where I just have the class, but not the ID.
document.getElementsByClassName('ep_price')[0]="FOO"
This should change the defined elemet to FOO, but it does not do that and I have no idea why not...
I have read that I should use .value, but this var is not even defined...
See Screenshot of my Chrome console below:
You need to use .textContent property if you intended to change the text.
document.getElementsByClassName('ep_price')[0].textContent ="FOO"
new Element does not work. Someone has any clue why?
css:
#tileNode {
position:absolute;
width:100px;
height:100px;
background-color:red;
}
js:
window.addEvent('domready', function() {
var newElement = new Element('div',{id:"tileNode"});
newElement.inject($$('div#tileNode'));
alert($$('#tileNode').get('id'));
});
Alerting #root works fine so it exists... creating that tileNode element does not work alerting it also does not work :/
Kind regards!
use
newElement.inject($('root'));
If you inject in the div with the id 'root',also you have to inject in a single element, use $('id') because the $$ returns an array…
There are few things in your code that took my attention:
Fist is, new Element('div',{id:"tileNode"}) is completely equal to new Element('div[id=tileNode]'). Since it makes no difference what way you choose, I'd recommend the second form, because it is a lot more readable. You could even add more attributes like Element('div[id=tileNode][class=tile]') and so on, instead of passing an object.
Another optimization would be to use the dollar function if you are trying to get an element by its id. So if you want to alert the id of an element, try to use alert($('tileNode').id).
Though alerting might work fine, you could try to use the javascript console. Instead of alert(myVar) use console.log(myVar).
Hope this helps, and happy coding :)
you can also use this to inject:
newElement.inject($$('div#tileNode')[0]);
folks,
I have on my pages (http://playdota.thilisar.cz) a JavaScript file(code below), that has to have an effect of modyfying the edge of the icons(for real, it has to load new picture) and loading the information(only plain text so far) into a div with ID "info" on mouseover event;on mouseout event it has to load the original picture to same position. But it only writes informations and replaces icons with "[object Object]" text.
I hope, you understand this, because my english isn't very good.
Thanks for your answers.
function showInfo(id){ //Using jQuery 1.7.2
document.getElementById('ses').innerHTML=$(function(){
$.ajax({
url: "sentinel_str/"+id+"-info.html"
}).done(function(data){
$("#info").html(data)
})
$("#ses").find("li").mouseover(function(){
$id=$(this).find("img").attr("id")
$(self.document[$id].src='look/icons/'+$id+'_hover.jpg')
})
$("#ses").find("li").mouseout(function(){
$id=$(this).find("img").attr("id")
$(self.document[$id].src='look/icons/'+$id+'.jpg')
})
})};
CLOSED THANKS TO CHEESEWARLOCK'S ANSWER
Thanks all, who tried to help me.
You are setting the innerHTML of the element to the value of the return of the jquery object. In effect you're saying put the 'toString' value of this function as the content of the HTML.
Do you mean to have? Unless I'm reading it wrong.
document.getElementById('ses').innerHTML=$(function(){
You're getting [object Object] because you're setting the contents of an HTML element to a jQuery object. If you want to call a piece of jQuery code, you don't need to wrap it in $(). You can just call the code directly. So get rid of this line:
document.getElementById('ses').innerHTML=$(function(){
and this line:
})
and the rest of your code will be executed when you call showInfo(id).
The "mouseover" and "mouseout" handlers look pretty confused to me. There's no need to call getElementById() at all; you're using jQuery, and you can find the <img> tags with it. Once you've found them, you've found them; no need to find them again.
$("#ses").find("li").mouseover(function(){
$(this).find('img').prop('src', function() {
return 'look/icons/' + this.id + '_hover.jpg';
});
})
$("#ses").find("li").mouseout(function(){
$(this).find('img').prop('src', function() {
return 'look/icons/' + this.id + '.jpg';
});
})
Passing a function as the second argument of .prop lets you compute the value of the property using the DOM element state directly.
Also you might want to use "mouseenter" and "mouseleave", which are sanitized by jQuery and are a little more reliable than "mouseover" and "mouseout".
edit — wow I just "zoomed out" and noticed that all this code is being set up as an innerHTML value, which makes no sense. Looks like a case of rampant copy/paste or something.
The code written below would solve your problem and is even short. Check it out once.
var id;
$('#ses').find('li').each(function(){
$(this).mouseover(function(){
var image=$(this).find('img');
id=$(this).find('img').attr('id');
$('#id').hide();
$(this).append('<div>'+id+'</div>');
});
$(this).mouseout(function(){
$(this).html('');
$('#id').show();
});
});
I'm trying to change HTML attributes using jQuery, but no matter what I do, I can't get anything to work with jQuery's .attr().
For testing, I've written
alert($("#logo").attr("title"));
and even though I have an img with id="logo" and a title, the alert remains blank.
My full method:
function switchVideo(videoID) {
var videoPlayer = document.getElementById("example_video_1");
videoPlayer.src = "video/Occam.webm";
videoPlayer.load();
$("#example_video_1").attr("poster", "video/ss.png");
//Doesn't work:
alert($("#logo").attr("title"));
$("#logo").fadeOut();
videoPlayer.play();
}
My fade out works, so I know I imported jQuery correctly.
I've gotten it working in another document, so there must be something else in the document messing it up. Does anyone know why this simple method won't work?
You can see the source page at http://jrstrauss.net/temp/create.html
Your div has the id logo, not the img.
Try:
$("#logo img").attr("title")
You should be using $.fn.prop for that now: http://api.jquery.com/prop/
You should use prop if you are using a recent version of jQuery.
You can also try this according to your HTML:
alert( $("#logo a img").attr("title") );
Demo
You have the following markup with id logo
<div id="logo">
......
</div>
Now, you are trying to run jQuery's .attr method by following code.
$("#logo").attr("title");
as you may know .attr method retrieves attribute value of the given element but that <div> doesn't have a attribute named title. so to confirm this, try retrieving attribute that does exist, for example id. so try this
alert($("#logo").attr("id"));
This will return the value of attribute. the important thing to note is jQuery looks for attributes of given element only, It doesn't scan child elements.
So, to make it work in your case. You need to do the following
alert($("#logo img").attr("title"));
Hope it helps
Well, I have this jQuery image slideshow that uses the attribute "control" inside an <a>. Seeing how it didn't validate I searched for a way to add this attribute inside my HMTL via jQuery but I didn't really find anything relevant. Now I don't really care about how valid my page is, but I'm really curious in how to add an HTML attribute inside an HTML tag.
In case I wasn't clear enough with my explanation, I have this code:
<a id="previous" control="-6" href="#"></a>
And I want to add control="-6" with jQuery.
Use jQuery's attr function
$("#previous").attr("control", "-6");
An example
// Try to retrieve the control attribute
// returns undefined because the attribute doesn't exists
$("#previous").attr("control");
// Set the control attribute
$("#previous").attr("control", "-6");
// Retrieve the control attribute (-6)
$("#previous").attr("control");
See this example on jsFiddle
You can alternatively use data function to store values on elements. Works the same way, for example:
$("#previous").data("control"); // undefined
$("#previous").data("control", "-6"); // set the element data
$("#previous").data("control"); // retrieve -6
Using data you can store more complex values like objects
$("#previos").data("control", { value: -6 });
($("#previos").data("control")).value; // -6
See a data example on jsFiddle
Since the jQuery version has been well covered here, I thought I'd offer something different, so here a native DOM API alternative:
document.getElementById('previous').setAttribute('control','-6');
Yes, I know you asked for jQuery. Never hurts to know the native way too. :o)
Let me see if I understood you.
You have, for example, the code:
<a id="previous" href="#"></a>
And by jQuery you want it to be:
<a id="previous" control="-6" href="#"></a>
Is it right?
If it is. You just have to do:
$('#previous').attr('control', -6);
If an attribute doesn't exists it's created by jQuery.
So, to remove it you can do:
$('#previous').removeAttr('control');
What you're doing doesn't respect the html rules and everything else, but it works fine, a lot of plugins do the same. ;D
I hope this could be helpful!
See you!
Try this:
$('#previous').attr('control', '-6');
Why? the $.attr(); function of jQuery allows you to add, get or update attributes (class, id, href, link, src, control and everything else!).
$("#previous").attr("control", "-6");
HTML:
<a id="previous" href="#">...</a>
jQuery:
$('#previous').attr('control', '-6');
jQuery's attr will do that. Example:
$("#previous").attr("control", "-6");
Also check out this example at http://jsfiddle.net/grfSN/.