I am a programming fool,
All I need is to be able to toggle two images, one which acts as the 'up state' of a button and then 'onclick' the second image appears and remains until it is clicked again whereby it is replaced by the the 'upstate image'.
Please don't mock me for this pitifull attempt which fails miserably. Here is my code.
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change()"/>
Thank you in anticipation.
Check this demo.
function change(image) {
if (image.src.indexOf("imgd1.svg") > -1){
image.src ="imgd1over.svg";
}
else{
image.src ="imgd1.svg";
}
}
In the fiddle case the image.src wasn't just the image's name, but the full url: http://fiddle.jshell.net/_display/imgd1.svg. So I have used indexOf() to check if the image's source constains the string you want.
Besides, I have changed the way change() function references to the image:
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change(this)"/>
Using change(this) will set the own image as the first parameter of the event, so you don't need to get it in the window object or event with getElementById or whatever.
function change() {
var image = document.getElementById("test");
if (image.src.indexOf("imgd1.svg") > -1 ){
image.src = "imgd1over.svg";
}
else if(image.src.indexOf("imgd1over.svg") > -1 ){
image.src = "imgd1.svg";
}
}
Here is the working code:
<img src ="imgd1.svg" name="pic" onclick="change();"/>
<script>
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
}
<script>
See the full demo:
http://jsfiddle.net/jswsze5q/
Try this:
<script>
function change() {
var img1 = "imgd1.svg",
img2 = "imgd1over.svg";
var imgElement = document.getElementById('test');
imgElement.src = (imgElement.src === img1)? img2 : img1;
}
</script>
<img src="imgd1.svg" id="test" onclick="change();"/>
Example: jsfiddle
Try using Jquery
var flag = 0;
function change(){
if(flag){
$("#img").attr("src","img1.png");
flag = 0;
}
else{
$("#img").attr("src","img2.png");
flag = 1;
}
}
Simplest toggle option
where variable flag acts as flag which detects which image is active
img is the id of image control.
Code to include Jquery from google CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Related
I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}
I need to change image when I click on it every time.
I added full path even it's not working.
<script type="text/javascript">
var imageon= document.getElementById("myElement");
function changeImage(){
if (imageon.src=="play1.gif"){
imageon.src="shutdown.png";
}
else if (imageon.src== "shutdown.png") {
imageon.src="play1.gif";
}
};
</script>
<img src="shutdown.png" id="myElement" onclick="changeImage();" style="width:95px"></img>
Javascript:
var pullImage=document.getElementById("change");
function changeImage(){
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif") {
pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png";
};
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png"){
pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif";
}
};
The problem is your path. I recreated the problem and i alerted the actual source which look like this:
You will either have to give the actual full path. Or you dont use the path as refrence, but a html reference. For example a hidden div with value 1 or 2 - for the used image
<div id="imgnumber">1</div>
<script>
var imagediv = document.getElementById("imgnumber");
var imageon= document.getElementById("myImg");
function changeImage(){
if (imagediv.innerHTML == "1"){
imageon.src="b.png";
imagediv.innerHTML = "2";
}
else if (imagediv.innerHTML == "2") {
imageon.src="a.gif";
imagediv.innerHTML = "1";
}
};
</script>
Please use below javascript and place it anywhere below tag you are using
<script type="text/javascript">
var imageon= document.getElementById("myElement");
function changeImage(){
var filename = imageon.src.replace( /^.*?([^\/]+)\..+?$/, '$1' );
if (filename=="play1"){
imageon.src="shutdown.jpg";
}
else if (filename== "shutdown") {
imageon.src="play1.jpg";
}
};
</script>
Using attr function you can change src of image :
$("#my_image").attr("src","second.jpg");
You can also create event eg. put thumbnail and on clicking load original image:
$('#my_image').on({
'click': function(){
$('#my_image').attr('src','second.jpg');
}
});
I have some code that makes an image larger when moused over:
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
}
</script>
and I call those functions with:
<a><img border="0" src="category_icons/addorder.png" onmouseover="bigImg(this)" onmouseout="normalImg(this)"></a>
But what I would really like to do is make it so the bigIMG(x) function also changes the image. I'm not extremely familiar with javascript and was wondering if someone knew what I can code in, to swap the image. The image name is addorder2.png. I've tried using this.src="addorder2.png"; but that is not working.
This will do. Change the image src into "addorder2.png".
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = " addorder.png";
}
</script>
My 2 cents:
LIVE DEMONSTRATION
Don't use inline JS, rather you can set a data.* attribute
and an object literal that will contain your desired changes
and read it with JS:
<img class="zoom" src="img.jpg" data-enlarge='{"src":"img2.jpg", "zoom":"1.2"}'>
As you can see above we'll target with JS every element with class "zoom"
function enlarge(){
var el = this,
src = el.src,
data = JSON.parse(el.dataset.enlarge);
el.src = data.src;
el.style.transition = "0.3s";
el.style.transform = "scale("+data.zoom+")";
el.addEventListener('mouseleave', function(){
el.src = src;
el.style.transform = "scale(1)";
},false);
}
var $ZOOM = document.querySelectorAll('.zoom');
for(var i=0; i<$ZOOM.length; i++){
$ZOOM[i].addEventListener('mouseenter', enlarge, false);
}
With Javascript you can edit the src attribute of the img.
Javascript:
function bigImg()
{
document.getElementById("myImg").src="addorder2.gif";
}
HTML:
<!DOCTYPE html>
<html>
<body>
<img id="myImg" onmouseover="bigImg()" src="addorder.png">
</body>
</html>
I recommend checking out w3schools to learn more about image document manipulation and of course specifically getting and setting the image src element
Just change x.src property according to function:
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "category_icons/addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = "category_icons/addorder.png";
}
Any One Know Tell me the suggestion to do this. How can i check if the anchor href attribute contain image path or some other path.
For Example:
<img src="image.jpg"/>
<img src="image.jpg"/>
See the above example shows href attribute contain different path like first one is the image and second one is the some other site link. I still confuse with that how can i check if the href path contain the image path or some other path using jquery or javascript.
Any suggestion would be great.
For example (you may need to include other pic formats if needed):
$("a").each(function(i, el) {
var href_value = el.href;
if (/\.(jpg|png|gif)$/.test(href_value)) {
console.log(href_value + " is a pic");
} else {
console.log(href_value + " is not a pic");
}
});
Jquery:
$(document).ready( function() {
var checkhref = $('a').attr('href');
var image_check = checkhref.substr(checkhref.length - 4)
http_tag = "http";
image = [".png",".jpg",".bmp"]
if(checkhref.search("http_tag") >= 0){
alert('Http!');
//Do something
}
if($.inArray(image_check, image) > -1){
alert('Image!');
//Do something
}
});
you may check if image exists or not, without jQuery
Fiddle
var imagesrc = 'http://domain.com/image.jpg';
function checkImage(src) {
var img = new Image();
img.onload = function() {
document.getElementById("iddiv").innerHTML = src +" exists";
};
img.onerror = function() {
document.getElementById("iddiv").innerHTML = src +"does not exists";
};
img.src = src; // fires off loading of image
return src;
}
checkImage(imagesrc);
I have this image in my html page:
<img src="/images/deactivate.png" onclick="act_deact(this);"/>
and in my javascript code i have this:
function act_deact(image) {
image.src = (image.src=="/images/activate.png" ) ? "/images/deactivate.png" : "/images/activate.png";
}
and when i click on the image that initially deactivated it activate but in the second click it doesn't desactivate !
is there any probleme with my code ?
from JS amateur :)
This is because when you set it to(or it changes to) /images/activate.png on first click, the src attribute is no longer just /images/activate.png but it gets prefixed with the server-address.
You can check it here: http://jsfiddle.net/hGcqq/
Or on your own server, use a console.log or an alert if you prefer.
#hjpotter92 already explained the reason it doesn't work.
One way to make it work is to check if src ends with /images/activate.png:
var activateURL = '/images/activate.png';
if (img.src.substring(img.src.length - activateURL.length) !== activateURL) {
image.src = '/images/activate.png';
} else {
image.src = '/images/deactivate.png';
}
The image.src contains the canonical path, even if initialised with a relative path. You can either use the full path in the condition like
function act_deact(image) {
image.src = (image.src=="FULL-PATH-OF-IMAGE" ) ? "/images/deactivate.png" : "images/activate.png";
}
(to get the full path one may use alert(image.src);)
or, if all your images have unique names
function act_deact(image) {
image.src = image.src.match(/activate.png$/) ? "/images/deactivate.png" : "images/activate.png";
}
The first thing is brackets which should be like this:
image.src = (image.src=="/images/activate.png" ? "/images/deactivate.png" : "/images/activate.png")
Also try image.getAttribute("src") and image.setAttribute("src") instead of image.src.
Please try this code:
function act_deact(image) {
image.setAttribute("src", (image.getAttribute("src")=="/images/activate.png" ? "/images/deactivate.png" : "/images/activate.png"))
}
Edit: other answers tell you about the issue of absolute and relative urls, so getAttribute will fix that issue. I do not recommend to use RegExp or substrings here.
To make it work with relative url you can simply save current url like this:
var newsrc = "/images/deactivate.png";
function act_deact(image) {
if ( newsrc == "/images/deactivate.png" ) {
image.src = "/images/activate.png";
newsrc = "/images/activate.png";
}
else {
image.src = "/images/deactivate.png";
newsrc = "/images/deactivate.png";
}
}
and then call it
<img src="/images/deactivate.png" onclick="act_deact(this);"/>
I found the solution myself :p and i have tried #fardjad proposition that is looking for string in the url and make conditions
i share the solution :)
function act_deact(image) {
if(image.src.indexOf('deactivate') != -1)
image.src="/images/activate.png";
else
image.src="/images/deactivate.png";
}
#hjpotter92: the solution with check condition on image.alt works to:
html:
<img alt="deactivate" src="/images/deactivate.png" onClick="act_deact(this);" />
the Js function :
function act_deact(image) {
if (image.alt=="activate") {
image.src = "/images/deactivate.png";
image.alt = "deactivate" }
else {
image.src = "/images/activate.png";
image.alt = "activate"
}
}
thanks for your responses :)