2 animated image buttons only 1 is working - javascript

I'm new to this but I'm sure this is an easy one. I'm trying to setup multiple animated image buttons on my website. I setup two test buttons, but only the second one is working. Both of them works fine by themselves but when I add them together only one works. What am I missing? Thanks in advance.
HTML:
<html>
<head>
<title>Default</title><script type="text/javascript" src="script.js"></script>
</head>
<body>
<div align="center"><br>
<img style="border: 0px solid ; width: 60px; height:60px;" alt="" src="clickA1.png" id="button1" onmouseover="rollover()" onmouseout="rollout()" onmousedown="down()" onmouseup="rollover()">
</div>
<br />
<div align="center"><br>
<img style="border: 0px solid ; width: 60px; height: 60px;" alt="" src="clickB1.png" id="button2" onmouseover="rollover()" onmouseout="rollout()" onmousedown="down()" onmouseup="rollover()">
</div>
<br />
</body></html>
Javascript:
<script>
function rollover () {
document.getElementById ("button1") .src = "clickA2.png"
}
function rollover () {
document.getElementById ("button2") .src = "clickB2.png"
}
function rollout () {
document.getElementById ("button1") .src = "clickA1.png"
}
function rollout () {
document.getElementById ("button2") .src = "clickB1.png"
}
function down () {
document.getElementById ("button1") .src = "clickA3.png"
}
function down () {
document.getElementById ("button2") .src = "clickB3.png"
}
</script>

You functions are over riding each other. Define a different name for the functions of button2
for example:
function rollover () {
document.getElementById ("button1") .src = "clickA2.png"
}
function rollover2 () {
document.getElementById ("button2") .src = "clickB2.png"
}

You have used multiple functions with the same name. In these cases functions written later overwrites the previous ones in the same scope.
A possible way is to include arguments inside your function calls
<button ... onmousedown="down('button1')" ...></button>
<button ... onmousedown="down('button2')" ...></button>
and handle them inside your function.
function down (button) {
document.getElementById (button) .src = "clickB3.png"
}
Or you can also detect which button was pressed from mousedown event.

You are writing two functions with the same name but different body. The 2nd one replaces the 1st implementation.

Related

how to change the src of an image when clicking and it return to the original after some time?

I have a page that displays several hidden divs when clicking on image-buttons (next and previous). sometimes takes a few seconds for its content to show up correctly, so I had the idea of ​​delaying the functions a bit to "give time" for the content to "prepare". While that time the image exchanges for a gif.
I already started and saw that it works, I got a simple way with tris.src to change the img and setInterval for the delay, direct on my onclick="", but I need the original image to automatically return to the original after 2 or 3 seconds because it can showed again (when clicked on previous button) and should not to be a gif anymore! and don't know how to do this. can you help me?
CSS:
div1, #div2 {width: 100px; height: 100px; background: yellow;position: relative;
next {position: absolute bottom: 20px; left: 20px}
}
HTML & JS:
<div id="div1">
content1
<img src="next.png" id="next" onclick="setTimeout(replace, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<div id="div2" style="display: none">content2
<img src="next.png" id="next" onclick="setTimeout(replace2, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<script>
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
function replace2() {
document.getElementById("div2").style.display="none";
document.getElementById("div1").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
</script>
You could just use a simple data attribute to store some state and swap in and out image source tags.
Here is an example of how this would work using JavaScript:
function clicked() {
replace();
setTimeout(replace, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
var current = document.getElementById("next").src;
document.getElementById("next").setAttribute("data-img-src", current);
document.getElementById("next").src = next;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>
If you need to account for multiple clicks and still return to the original image you will need some more state and can try this:
function clicked() {
replace();
setTimeout(replaceOriginal, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
document.getElementById("next").src = next;
}
function replaceOriginal(){
var original = document.getElementById("next").getAttribute("data-img-original");
document.getElementById("next").src = original;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-original="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>

How to get event target/this without putting the event listener in the HTML tag? [duplicate]

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>

How to make an onclick function change the src for two images

I'm supposed to add script to an HTML file so that when I click the first star in the star rating system, it will change the src to 'star-on.png' as opposed to 'star-off.png'. That, I can do. But I can't figure out how to make it so that if the user clicks the second star, it will change the src for both the first and the second star to 'star-on.png'.
Here's the code that my teacher provided:
<!-- 1. PUT YOUR NAME IN THIS COMMENT -->
<html>
<head>
<!-- 2. DO NOT EDIT THE CSS -->
<style type="text/css">
body {
margin: 0;
}
div {
width: 520px;
display: block;
margin-left: auto;
margin-right: auto;
}
img {
width: 100px;
}
</style>
<!-- 2.5 YOU MAY ALTER THE STYLING OF THE BUTTON IF YOU WISH. -->
<style type="text/css">
button {
width: 200px;
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<!-- 3. DO NOT ALTER THE HTML EXCEPT TO ADD ONCLICK, ONLOAD, AND SIMILAR ATTRIBUTES -->
<!-- AS NEEDED -->
<body>
<div>
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
<img src="star-off.png" id="three">
<img src="star-off.png" id="four">
<img src="star-off.png" id="five">
</div>
<button id="reset" onclick="document.getElementById('one').src='star-off.png'">Reset</button>
<!-- 4. YOU MAY PUT YOUR SCRIPTING HERE -->
<script>
document.getElementById('one').onclick = function () {
document.getElementById('one').src="star-on.png";
}
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
document.getElementById('three').onclick = function () {
document.getElementById('three').src="star-on.png";
}
document.getElementById('four').onclick = function () {
document.getElementById('four').src="star-on.png";
}
document.getElementById('five').onclick = function () {
document.getElementById('five').src="star-on.png";
}
</script>
</body>
</html>
Except for the things inside the script tag and the onclick inside of the button, it's all my teacher's code.
This is what it looks like:
Well, you've really got most of what you're trying to do in your script already. Look at each of these lines:
document.getElementById('one').onclick = function () {
document.getElementById('one').src="star-on.png";
}
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
document.getElementById('three').onclick = function () {
document.getElementById('three').src="star-on.png";
}
document.getElementById('four').onclick = function () {
document.getElementById('four').src="star-on.png";
}
document.getElementById('five').onclick = function () {
document.getElementById('five').src="star-on.png";
}
Essentially, each one is saying select the element by its Id attribute, identified in the preceding group by the 'id=""' in this part:
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
<img src="star-off.png" id="three">
<img src="star-off.png" id="four">
<img src="star-off.png" id="five">
and then attach an onclick event to it. When that onclick event fires, do the function that you've defined to the right of each of the equal signs following the event specification.
Inside each of your functions, it is simply going to identify the element on the DOM that matches the element id you're providing (just as you already did to assign the event handler in the previous section) and you're going to change the value for its 'src' attribute to the string you're defining on the right side of the equals.
Take the second one, per your request. Here's the HTML you're referencing (for both the first and second stars):
<img src="star-off.png" id="one" class="2">
<img src="star-off.png" id="two" class="2">
And here is the event handler you've already got in place for the second one:
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
}
Right now if you click on that second star, you're only changing the src attribute of the element with an ID of 'two' to the 'star-on.png' image. So, if you want to also change the element of the star before it, it's got an ID of 'one', so you'll need to add this line within the event handler.
document.getElementById('one').src = "star-on.png";
Sure, there are more efficient ways to do this, but undoubtedly you'll learn about them as your course progresses. Here's what your event handler will look like with this update:
document.getElementById('two').onclick = function () {
document.getElementById('two').src="star-on.png";
document.getElementById('one').src = "star-on.png";
}

I want to change background of div onclick

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+")");
});

html multiselect images

I printed to the screen 16 icons (little pictures).
Now I want to be able to select icons,
and when I press a button the selected icons ids will be sent in a form.
I saw in the net only checkboxes and lists multiselect,
what's the best way to do this?
(I'm pretty new to web design)
thanks ahead!
Although jQuery isn't in your tags, you should introduce yourself to jQuery. It'll make your life easier, for what you're trying to do. Here is the basic steps both if you use jQuery and if use just Javascript:
With jQuery
Give all your icons a class and each one a unique id:
<img src='icon1.png' data-iconID=2233 class='myIcons' />).
Then bind that class to a click event
$('.myIcons').bind('click', function() {
$(this).toggleClass('selectIcon');
});
Attach form submit function to onsubmit:
<form ... onsubmit="submitForm();">
Build submitForm function:
function submitForm() {
var csvIconIds = '';
$.each($('.myIcons.selectIcon'), function (index, value) {
csvIconIds += $(value).attr('data-iconID');
});
//submit scvIconIds here along with other form data (ajax?)
}
With Javascript
Similar as above but way more complicated...
To toggle classes see this thread: How to add/remove a class in JavaScript?
To getting attributes by class see this site: http://www.actiononline.biz/web/code/how-to-getelementsbyclass-in-javascript-the-code/
This could be a way using just plain Javascript or jQuery. I prefer the jQuery version, since it separates the click handler from the markup, instead of using inline onclick handlers, which are in general discouraged.
What this does is use an input element array, which you can create by adding [] to the element name. This same technique can be used on SELECTs and other elements, since it signals to the server that an array has been submitted, as opposed to value known by a single key.
<html>
<head>
<style type="text/css">
div img {
cursor: pointer;
border: 1px solid #f00;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script>
function setFormImage(id) {
if (id != '' && !document.getElementById('input_'+id)) {
var img = document.createElement('input');
img.type = 'text';
img.id = 'input_'+id;
img.name = 'images[]';
img.value = id;
document.imageSubmit.appendChild(img);
}
}
$(document).ready(function(){
$('#jqueryimages img').click(function(){
setFormImage(this.id);
});
});
</script>
</head>
<body>
<pre><?php
if (count($_GET['images'])) {
print_r($_GET['images']);
}
?></pre>
<div style="float: left; width: 49%;">
<h1>Plain ol' HTML</h1>
1. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-1" onclick="setFormImage(this.id)"/>
<br/>
2. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-2" onclick="setFormImage(this.id)"/>
<br/>
3. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-3" onclick="setFormImage(this.id)"/>
<br/>
4. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-4" onclick="setFormImage(this.id)"/>
</div>
<div id="jqueryimages" style="float: left; width: 49%;">
<h1>jQuery</h1>
5. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-5"/>
<br/>
6. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-6"/>
<br/>
7. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-7"/>
<br/>
8. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-8"/>
</div>
<h1>Form Submit</h1>
<form name="imageSubmit" method="get">
<input type="submit" value="View Selected"/>
</form>
</body>
</html>
try this
var idArray = [];
$("#container-id img").each(function(index,value){
idArray.push($(value).attr("id"));
});
//do anything with the array

Categories