How to get an attribute from a hierarchy? (read) - javascript

I've got the following code (example):
<body>
<div id="obj1">
<span id="obj2">
<img src="someimage2.jpg" class="image" />
</span>
<img src="someimage2.jpg" class="image" />
</div>
<img src="someimage3.jpg" class="image" />
<button onClick="getUrl();">Get it?</button>
</body>
I need JavaScript to get the url of the image which is located at body >> obj1 >> obj2 >> img
I can imagine a markup similar to this...
function getUrl() {
alert(document.getElementById("obj1").getElementById("obj2").img.getAttribute("src"));
}
But (what a surprise!) it doesn't work, apparently.
Any help? :)
What I am trying to do (if this helps):
I've got an input and a button. Say I type this into input:
Cyber Dragon
This code is called upon the button is pressed:
'do something' or here: document.write('<input id="src" /><button onClick="getImg();">Get</button><br /><iframe src="http://yugioh.wikia.com/wiki/' + document.getElementById("src").value.replace(" ","_") + '"></iframe>');
Then, I'd need to get the image's src attribute from the site (which is "http://yugioh.wikia.com/wiki/Cyber_Dragon" in this case), but it's not all that simple.
The site stores it in an img, not an ID's Div, and can only be told from other images by its hierarchy position. Also, the img's src is complicated and not universal. For example, one's adress would be
http://images3.wikia.nocookie.net/__cb20060929013607/yugioh/images/thumb/e/e5/CyberDragonCRV-EN-SR.jpg/300px-CyberDragonCRV-EN-SR.jpg
and another would look like
http://images1.wikia.nocookie.net/__cb20090402012158/yugioh/images/thumb/a/a6/HonestLODT-EN-ScR-1E.png/300px-HonestLODT-EN-ScR-1E.png

Since you can only have one element in any document with any given id, you only need the one getElementById. You can then use getElementsByTagName to find the image and then the src property to find the image's source:
var imgsrc = document.getElementById('obj2').getElementsByTagName('img')[0].src;

Related

Jquery dynamically enter values

below is my code
<img src="1.gif"></i>
<img src="2.gif">
as shown in the above code when user clicks on smiley image it changes the value of text area #chat_textarea values are different for different smiley images,above code works fine... but what if i have more then 100 smileys? is there any way i can change the value of chat_textarea dynamically...? because to load images Iam just for loop which loads all images 1 to given number...
Updated:Hi all I know that we can use classname
$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});
But my question is different...i can not add alt / value to each image, it should be loaded automatically,something like fetching ;) from json file by passing id ....is there any ways to fix in that way....
Below some simpeler html.
If you want to load them dynamicly, just use your language of choice to loop through an array:
// Php
foreach($smileys as $img=>$code){ echo '<img src="'.$img.'" alt="'.$code.'" />';}
// Javascript
$.each(smileys, funcion(index,smile){
$('#smileWrap').append('<img src="'+smile.src+'" alt="'+smile.alt+'" />')
});
<img class="add_smile" src="/img1.jpg" alt=":)" />
<img class="add_smile" src="/img2.jpg" alt=":(" />
<img class="add_smile" src="/img3.jpg" alt=";)" />
$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});
jQuery doesnt care what you add the click to, the image is just fine. If you want a pointer as mouse, just css that.
Now you can use php to loop and place as many images as needed. Images are required to have an alt, that's fixed. And we can easily access it in javascript, not needing extra html (the anchor) to get that.
My jsFiddle, with auto space-add if not present
Remove unnecessary links, add a ClassName and a data-val attribute to each smiley and modify your HTML like this:
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
Then use this JQuery:
$('.smiles_btn').click(function(){
$('#chat_textarea').val($('#chat_textarea').val() + ' ' + $(this).data('val')).focus();
});
Check JSFiddle Demo

jQuery script for image change, not working

I want to change src of in img, I coded as below, but it's not working, what's wrong?
<img id='logo_image'/>
<span onclick='$(logo_image).attr("src", "images/logo_orange.png");'>click me</span>
It might be the problem with your selector.
If it is id use $('#logo_image')
If it is class use $('.logo_image')
First up you're trying to use a variable logo_image when you should be using a string starting with # to indicate you want to select by id:
onclick='$("#logo_image").attr("src", "images/logo_orange.png");'
Secondly, it would be better not to use an inline onclick attribute if you can help it:
<img id='logo_image'/>
<span>click me</span>
<script>
$("span").click(function() {
$("#logo_image").attr("src", "images/logo_orange.png");
});
</script>
...where ideally the span element would have some id or something to select it by.
Thirdly, don't make span elements clickable in the first place unless you don't care about making your page accessible to people who can't (or who choose not to) use a mouse or other pointing device. Better to use an anchor (which you can style as you see fit) so that the user can tab to it and activate it with the keyboard:
<img id='logo_image'/>
click me
<script>
$("a").click(function(e) {
e.preventDefault();
$("#logo_image").attr("src", "images/logo_orange.png");
});
</script>
The problem with your code is you aren't probably setting the object to logo_image variable.
I suggest changing it to:
<span onclick='$("#logo_image").attr("src", "images/logo_orange.png");'>click me</span>
logo-_image should be the id of that image.
Since you want refer to the name of the id, you have to wrap the logo_image in quotes, otherwise Javascript will treat it as variable.
$('#logo_image')
You have to use something like this:
<img id="logo_image" src="" />
<span onclick='$("#logo_image").attr("src", "images/logo_orange.png");'>
click me
</span>
if you have an img with a id named logo_image
if your img has the css class logo_image you have to write:
<img class="logo_image" src="" />
<span onclick='$(".logo_image").attr("src", "images/logo_orange.png");'>
click me
</span>
Make sure u use the right quotes in the javascript part.
Also use $('#logo_image') selector to get the image by id.
I made a jsfiddle for you to demonstrate:
http://jsfiddle.net/9Ltfa/
<span onclick="$('#logo_image').attr('src', 'images/logo_orange.png');">click me</span>
As you have specified the image as an id, you will need to reference the image via the following code:
$('#logo_image')

javascript change Image by clicking thumbnail

I am a newbie in javascript and tried a lot of things for hours, but nothing worked.
I will change a big imgage by clicking on a thumbnail.
Untill now I got following script. Not much really... :-(
<script type="text/javascript">
function changeImage() {
document.getElementById("img").src="img/upload/test1.jpg";
}
</script>
<img id="img" name="change" src="img/upload/test.jpg">
<img src="img/thumbnail/test.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
<img src="img/thumbnail/test1.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
All big picture are under src"img/upload/xxx.jpg" and all thumbnails under src="img/thumbnail/xxx.jpg". When I click the thumbnail, it have to change the big picture and it have to give the parameter in the javascript. Like onclick="changeImage(xxx.jpg).
The problem is every page have other pictures. I get them from a database. So the name of the picture is like a variable. I hope you understand. It is hard for me to explain. :-(
Thanks for your help in advance.
Greets Yanick
Pass the image parameter to the function like,
function changeImage(image) {
document.getElementById("img").src=image;
}
<img src="img/thumbnail/test.jpg" alt="" id="img"
onclick="changeImage('img/upload/test1.jpg')" />
Keep ids unique. DOM elements "must" possess unique IDs for all practical reasons.
Though you could do an inline onclick, a better way to proceed with it is something as follows.
Assuming you have the images generated from some templating library either on the client or from the server, add data attributes with the image sources and a common class to all of these elements right there and add an event listener from your Javascript bound to elements matching the class and picking up the data attribute to replace the image source.

Whether DOM property will work for Phone Gap android?

I am working on a Phonegap android project.
I would like to know whether the DOM property will work for Phone Gap or not.Because,I tried implementing a condition such as
if(results.rows.item(val[1]).COLUMN_NAME==="")
{
document.getElementById("ID").src="img/abc.png";
console.log("abc image to be changed"+val[1]);
}
else
{
document.getElementById("ID").src="img/abc1.png";
console.log("no change "+val[1]);
}
HTML CODE:
I tried executing the program in 2 of the following cases in HTML
CASE 1:
<div id="ID" > <img src="img/abc1.png" onclick="abc()" /></div>
CASE 2:
<div id="ID" > <img src="" onclick="abc()" /></div>
when i run the program the Console statement is being displayed,but there is no change in the image.
AM I RIGHT IN THE WAY OF IMPLEMENTATION?
please guide.
div doesn't have the attribute src. so you need to give the id to img tag to change the src of image like that:
<div> <img src="img/abc1.png" id="ID" onclick="abc()" /></div>
Or you can change the image by the innerHTML property like this:
document.getElementById("ID").innerHTML = '<img src="img/abc.png" onclick="abc()" />';
Use any one which you want.
div tag does't have any src attribute .src attribute is img tag property . so get that id inside img tag . then only you can change the src attribute

Show something that was hidden by default?

I have this code for a small jQuery game I'm making, and all the pictures (characters) are hidden by default. There's a question that says "Are you ready to play?" and a yes or no button. When you click the yes button, it hides the buttons and the text. It is also supposed to display the first image, which is #main. For some reason, it's not working.
Here's the jQuery code with the images under:
$(document).ready(function(){
$('#main,#batman,#car,#hobo,#knife,#gangfight,#ganggun,#gangknife,#blood').hide(-100);
var main=$('#main');
batman=$('#batman');
car=$('#car');
hobo=$('#hobo');
cop=$('#cop');
knife=$('#knife');
gangfight=$('#gangfight');
ganggun=$('#ganggun');
gangknife=$('#gangknife');
blood=$('#blood');
document.write('<title>LOAUP</title>');
document.write('<center><h1>The life of an unlucky person</h1></center>');
document.write('<center id="start">Are you ready to play?</center>');
document.write('<center><button id="yes">Yes</button><button id="no">No</button></center>');
$('#yes').click(function(){
$('#yes,#no').hide(function(){
$('#start').hide();
$('#main').show
});
});
$('#no').click(function(){
$('#yes,#no').hide();
$('#start').hide();
document.write('<center>Ok, come back another time then.</center>');
});
});
//Images below this (HTML)
<img id='main' src='/jquery/sprites/spritePerson.png' />
<img id='batman' src='/jquery/sprites/spriteBatman.png' />
<img id='car' src='/jquery/sprites/spriteCar.png' />
<img id='hobo' src='/jquery/sprites/spriteHobo.png' />
<img id='cop' src='/jquery/sprites/spriteCop.png' />
<img id='knife' src='/jquery/sprites/spriteKnife.png' />
<img id='gangfight' src='/jquery/sprites/spriteGangFight.png' />
<img id='ganggun' src='/jquery/sprites/spriteGangGun.png' />
<img id='gangknife' src='/jquery/sprites/spriteGangKnife.png' />
<img id='blood' src='/jquery/sprites/spriteBloodPuddle.png' />
Edit:
Here's the example:
http://jsbin.com/ocowas/1
In your #main click function change
$('#main').show
to
$('#main').show();
Your variable list should be comma seperated not colon seperated. and you may also want to rename your variables to make them more obvious and easier to read/remember by prefixing with a $ sign. For example when you store a selector as a variable use
var $element = $('#element'),
$element2 = $('#element2'),
$element23 = $('#element23');
Further, the hide() function does not take negative numbers as you have used. Just use hide() for an instant hide, or hide(100) for fast, hide(2000) for slow.. check: http://docs.jquery.com/Effects/hide
To append html to your document without using document.write, you can store the html as a variable, then select the body tag, or any other tag and append/prepend or replace the html to that, for example.
$('body').append(yourHTMLvar);
$('body').prepend(yourHTMLvar);
$('body').html(yourHTMLvar);
The 'title' tag should only appear between the 'head' tags of your html document. Use a heading tag instead, 'h1' to 'h6'.
The html 'center' tag is also deprecated as far as I know. Try using 'span', 'p' or even 'div' instead.

Categories