javascript change Image by clicking thumbnail - javascript

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.

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

How to replace multiple images with Javascript and change back

I've been working on trying to get these buttons to change when clicked - which now works, but now I need them to toggle between the on and off states when the user clicks (so they can turn the buttons on and off). I'm sure this is an easy fix, but I'm new to Javascript and I don't have anyone to bounce ideas off of.
<html>
<head>
<script type="text/javascript">
function changeimage(img, new_src)
{
var cur_src = img.src.substring(img.src.lastIndexOf("/")+1);
if (cur_src == new_src)
{
img.src = img.old_src;
}
else
{
img.old_src = cur_src;
img.src = new_src;
}
}
</script>
</head>
<body>
<img onclick="changeimage(this, 'images/buttonA_on.png')" src="images/buttonA_off.png" />
<img onclick="changeimage(this, 'images/buttonB_on.png')" src="images/buttonB_off.png" />
<img onclick="changeimage(this, 'images/buttonC_on.png')" src="images/buttonC_off.png" />
<img onclick="changeimage(this, 'images/buttonD_on.png')" src="images/buttonD_off.png" />
<img onclick="changeimage(this, 'images/buttonE_on.png')" src="images/buttonE_off.png" />
<img onclick="changeimage(this, 'images/buttonF_on.png')" src="images/buttonF_off.png" />
</body>
</html>
Much thanks!
When I started using JavaScript I wasted a bunch of time trying to do things that other libraries could easily take care of for me. A few months after that I discovered jQuery which has drastically reduced the amount of time I spend on front-end projects. All you have to do is include the jQuery file in an html project and you're good to go.
In jQuery, you can toggle a class on and off with one line. it looks something like this:
$('.toggleimage').toggleClass('on');
In the above example, '.toggleimage' is just a class I gave to a div, toggleClass is the jQuery command, and 'on' is the name of the class I want to toggle. This probably seems like greek right now, but I recommend going through codeschool's jQuery tutorials to get caught up. If you're thinking of doing serious web development... it's a crucial tool. Here is the full code:
link to full code on my Gist
In order to make it work, make sure you have the right file structure. Create a folder, then create the html file there. In addition, create three subfolders (one for css, one for images, one for scripts). The css folder holds your style.css, the images folder holds mario.jpg, and the scripts folder contains your jQuery file. You can substitute in any image you want, just make sure the changes are applied to style.css.
function changeImg(img) {
if ( img.src.indexOf("_off") > 0 ) {
img.src = img.src.replace("_off","_on");
}
else {
img.src = img.src.replace("_on","_off");
}
}
it will work if you have 50x2 different images, named "imgName1_uw.jpg", "img1_moored.jpg", "img2_uw.jpg", "img2_moored.jpg", etc.
may be its helps you

How do I pass a string from Javascript to the src part of an image tag in HTML?

I've written an extremely simple Javascript function. All it does is randomly selects an image filename (file.png, for example) and and passes it over with getElementById.
var nameA=fileNames[randnumA];
document.getElementByID("image1").firstChild.nodeValue= nameA;
Of course, there's other stuff to go along with that, but I didn't feel it necessary to be included. All I'm doing is passing a string over from Javascript. Simple enough.
The problem is that I want to use that string as the source for an HTML tag. I'm a noob, and haven't done this before, so a simple explanation would be awesome. My current code in HTML is this:
<img src=<span id="image1"> </span>>
I didn't expect it to work, as placing tags within other tags doesn't feel right.
Any ideas as to how I'm supposed to do this? Thanks everybody, I appreciate the help.
Also, the function is definitely being called. I have it as an onLoad in the <body> tag.
blank stare
<img id="image1" />
JS:
var nameA = fileNames[randnumA];
document.getElementById('image1').src = nameA;
Javascript:
var nameA=fileNames[randnumA];
document.getElementByID("image1").src = nameA;
HTML:
<img id="image1" />

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.

Grails: JS function to change src of img is not responding

I am trying to change the src of an img under a certain condition. I know the condition returns true appropriately, because I previously wrote in an alert(). For some reason, the function is not changing the src of the img and dynamically updating the page. Could this have anything to do with the fact that I am using the jquery library? I would think you can still use the stand js syntax. Here are my code snippets and the corresponding source code from google chrome.
.gsp:
<script type="text/javascript">
function onSuccess(data){
if(data.hasHearted){
document.getElementById("changer${user.id}").src = "${resource(dir: "images/images", file: "heart_red.png")}";
}
}
<figcaption id="secondcap" onClick="${remoteFunction(controller:'user', action:'heart', onSuccess: 'onSuccess(data)', params:[userID:user.id])}">
<img id="changer${user.id}" src="${resource(dir: "images/images", file: "heart.png")}" alt="heart">
</figcaption>
Chrome source (I've omitted some things for privacy):
<script type="text/javascript">
function onSuccess(data){
if(data.hasHearted){
$('#changer3').attr('src','/Personably/static/images/images/heart_red.png');
}
}
</script>
<div class="persons">
<figure class="user_image">
<img class="user_profile_pic" src="omitted for privacy..." onmouseover="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/hasHearted',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});"/>
<figcaption id="firstcap">
Omitted for privacy...
</figcaption>
<figcaption id="secondcap" onClick="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/heart',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});">
<img id="changer3" src="/Personably/static/images/images/heart.png" alt="heart">
</figcaption>
</figure>
</div>
Since you are using jquery, have you tried using the jquery id selector $(“#id”) and/or the jquery .attr function?
http://api.jquery.com/id-selector/
http://api.jquery.com/attr/#attr2
I'm not sure that changing the src attribute after the page is loaded will change what the user sees, even if it changes the code, because the document is already loaded.
Instead, you should probably put both images (heart.png and heart_red.png) on the page, and then hide/unhide them with styles depending on the output of your controller action. The jquery .toggle(Boolean) method can be very useful for stuff like this. http://api.jquery.com/toggle/
Inside your JavaScript function, you could just have something like:
$('#heart3').toggle(!data.hearted);
$('#heart_red3').toggle(data.hearted);
Then, when data.hearted is true, red heart will show, and plain heart will hide.

Categories