In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.
The first image has an id of chrome and when clicked I'm trying to change the image.
https://codepen.io/centem/pen/NgKEmG
Here is the js I'm using.
function changeImage() {
if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
{
document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
}
else
{
document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
}
}
Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.
Change <img onclick()="changeImage()"> to <img onclick="changeImage()">
First off, change the <img onclick()="changeImage()" to <img onclick="changeImage()". That doesn't solve your problem if you want to do it for multiple users, as each one of the chrome images needs it's own ID for the function to work on more than one logo.
You had a typo. When defining an inline onclick you have written:
<div onclick()="changeImage()"></div>
It should be:
<div onclick="changeImage()"></div>
See snippet below:
function changeImage() {
if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
{
document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
}
else
{
document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
}
}
img {
height: 25px;
padding-right: 4px;
}
li {
margin: 4px;
clear: both;
}
li:nth-child(odd) {
background: #f0f0f5;
}
<ul class="list-unstyled">
<li>Username<span class="pull-right">
<img onclick="changeImage()" id ="chrome" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right"><img id="firefox" src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img id="ie" src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>
</ul>
Instead of onclick()="changeImage()";.... Use onclick="changeImage()".....Remove "()" bracket in onclick function
You have a syntax error in your HTML code. onclick is not a function, it is an HTML attribute, so you don't call it like a function by adding parentheses to it.
You only to that to the value of the onclick attribute, which is JavaScript syntax.
The correct code is:
<img onclick="changeImage()">
Here is a working version of your code pen: https://codepen.io/pahund/pen/XgWVQx
Related
This question already has answers here:
Get clicked element using jQuery on event?
(6 answers)
Closed 5 years ago.
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use
$(document).ready(function(){})
I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?
//$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>
Thanks in advance!
PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.
PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D
PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)
Firstly you need to define function() in a click function so it should look like this:
$("button").click(function() {
//code to execute here
});
Instead of this:
$("button").click(//code to execute here);
When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.
To use this you also need to call it as $(this) not just this.
This should work.
//$(document).ready(function() {
window.onload = startup();
function startup() {
console.log("window loaded");
$("img").hide();
$("button").click(function() {showImage(this)});
}
function showImage(e) {
console.log("onside eras");
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:
var chosen = $(this).prop('value');
I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.
UPDATE
Just saw your commented out code:
$("button").click(showImage(this)); // When a button is clicked
// call the function returned by showImage(this).. err it doesnt return
// a function so it fails.
you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.
It should actually be:
$("button").click(showImage); // when a button is clicked
// call the function showImage with this=<clicked button> and param=event
and this will be automatically set inside the function as event.currentTarget
$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = $(this).prop('value');
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
$('.myclass').on('click', showImage);
});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>
I'm trying to make a simple page that lets me input a name and a photo pops up figured javascript would accomplish that but i'm a javascript newbie and need some help :( here is my code:
<img id="myImg"
src="https:placeholderlink"
width='500'
alt='Not Loaded' onmouseOver="this.width=550" onmouseOut="this.width=500" />
CBName: <input type="text" id="CBName" name="CBNameBox">
<button onclick="myFunction()">Submit</button>
<script>
function CBNameChanger() {
var Source = document.getElementById("CBName").value;
var itemName;
{
document.write(itemName);
}
function myFunction() {
document.getElementById("myImg").src = "https:placeholderlink" + itemName ;
}
}
</script>
as you see i need to code the take my input and add it to the end of the img url
i was trying to make my image enlarge when you hover the mouse over also that works when an img is present but i cant get an image to load and dont know what im doing wrong lol this is hack an slash code i pieced together from google searches
any help at all would be appreciated!
You almost got it, only you had to do is to join both functions and remove the weird document.write between braces.
function CBNameChanger() {
var Source = document.getElementById("CBName").value;
document.getElementById("myImg").src = "http://lorempixel.com/" + Source;
}
#myImg {
width: 50px;
height: 50px;
}
<img id="myImg" src="http://lorempixel.com/" width='500' alt="Not Loaded" onmouseOver="this.width=550" onmouseOut="this.width=500" />
<br> CBName: <input type="text" id="CBName" name="CBNameBox" value="50/50/">
<button onclick="CBNameChanger()">Submit</button>
I have placed an image inside a div element and I'm setting a clicklistener on it, but the method onGermanFlagClicked does not execute.
<div style="position: absolute; top: 10px; padding-left: 10px;" id="de">
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/b/ba/Flag_of_Germany.svg/1280px-Flag_of_Germany.svg.png" heigth="50px" width="50px"/>
</div>
<script>
var germanFlag = document.getElementById("de");
germanFlag.addEventListener("onclick", onGermanFlagClicked);
/* Changing language here */
function onGermanFlagClicked(event){
event.preventDefault();
console.log("clicked");
}
</script>
How can I fix this?
It's: germanFlag.addEventListener("click", onGermanFlagClicked);
not germanFlag.addEventListener("onclick", onGermanFlagClicked);. Check this out.
change germanFlag.addEventListener("onclick", onGermanFlagClicked); line to
germanFlag.addEventListener("click", onGermanFlagClicked);
Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".
here is the list of all valid DOM events.
Check here for more on JavaScript HTML DOM EventListener.
I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much
How to get clicked image as background of div? I new to javascript. I tried using onclick but the code did not work.I hope may be due to programming mistakes.
<div id="canvas"></div>
<div id="containerA">
<div id="one" ><img src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg" id="image" onclick="change();"/></div>
function change(){
document.getElementById("image").style.backgroundImage = this('src');
};
change your code to this -
<div id="canvas"></div>
<div id="containerA">
<div id="one" ><img src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg" id="image" onclick="change(this);"/></div> // passed this to the parameter
function change(obj){
document.getElementById("canvas").style.backgroundImage = obj.src; // here
};
You declared a function, but you didn't ask it to run. Try this or the code snippet below. Also, you can separate codes in order to control well.
function changeImg() {
document.getElementById("canvas").style.background = "url('//stephboreldesign.com/wp-content/uploads/2012/03/lorem-ipsum-logo.jpg')"
}
document.getElementById("canvas").onclick = changeImg;
#canvas { /* just for test, you can change by yourself */
width: 325px;
height: 325px;
background: red;
}
<div id="canvas"></div>
And here on JSBin is another version if you'd like to change the background between two images, or more. Below are some references for you to know more about function used in example.
W3C School - style change, W3C School - onclick event
MDN - style change, MDN - onclick event
Pass this to the onclick function like this
<div id="canvas"></div>
<div id="containerA">
<div id="one" ><img src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg" id="image" onclick="change(this);"/></div>
</div>
And this is what you do in the Javascript function
function change(img){
var urlString = 'url(' + img.src + ')';
document.getElementById("canvas").style.backgroundImage =urlString;
};
And this should definitely work!
1.you didnt added Jquery
2. On click of image you are calling "change" method but you have to correct the method name.
In below image check the red rectangles for errors-
function changeImage(imgObj){
bgImage = imgObj.src;
$("#updateDiv").css('background-image','url('+bgImage+')');
}
http://plnkr.co/edit/RL7T0a?p=preview
I would suggest to use jQuery in your project. With jQuery something like this could work:
var imageSource = "";
$("#img").click(function(){
imageSource = $(this).attr("src");
$('#canvas').css("background-image", "url("+imageSource+")");
});