Changing div background image by clicking on specific button - javascript

Im trying to make a page where the background image of the div element changes once I click a button.
document.getElementById("one").addEventListener("click", photo);
document.getElementById("two").addEventListener("click", photo);
document.getElementById("three").addEventListener("click", photo);
document.getElementById("four").addEventListener("click", photo);
function photo()
{
var photograf= document.getElementById("photodiv");
var x= document.getElementById("one");
var y= document.getElementById("two");
var z= document.getElementById("three");
var t= document.getElementById("four");
if (x.click) {photograf.style.backgroundImage= "url('1.png')";}
else if (y.click) {photograf.style.backgroundImage= "url('2.png')";}
else if (z.click) {photograf.style.backgroundImage= "url('3.png')";}
else if (t.click) {photograf.style.backgroundImage= "url('4.png')";}
else {photograf.style.backgroundImage= "none";
}}
div id="photodiv">
</div>
<input type="button" value="1" id="one">
<input type="button" value="2" id="two">
<input type="button" value="3" id="three">
<input type="button" value="4" id="four">
The problem is once I try to click on the buttons the only photo that appears is "1.png" no matter what button I click.
Does anyone have an idea how this could be solved?

The problem is that you are testing x.click, y.click, etc. which is not actually testing to see which button got clicked, but instead is testing to see if each element has a click method, which they all do, but because the first one you test is x.click and that test returns true, that's the one that runs all the time.
The code can be simplified quite a bit with no if/then needed at all. And, all you'd have to do to add more choices is just add another button and add the new image path into the array.
See the comments inline below:
// Instead of setting up 4 separate event handlers that all point to the
// same callback function, we can use event delegation where we handle the
// event on an ancestor object of all the elements we care about
document.querySelector(".buttonContainer").addEventListener("click", photo);
// Store all the images in an array
var backgrounds = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/220px-SNice.svg.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
"https://www.qualitylogoproducts.com/stress-balls/smileyface-squeezie-superextralarge-480745.jpg",
"https://cmkt-image-prd.global.ssl.fastly.net/0.1.0/ps/3647668/1160/1160/m1/fpnw/wm1/10837-royalty-free-rf-clipart-illustration-black-and-white-smiley-face-cartoon-character-vector-illustration-isolated-on-white-background-.jpg?1511798933&s=2e423029fc4d833fde26d36d8a064124"
];
// Get a reference to the output element
var picHolder = document.getElementById("photodiv");
// All event handling functions are automatically passed an argument
// that is a reference to the event object itself
function photo(event){
// Just set the background image based on the index of the button
// that got clicked within its parent and the corresponding index
// of the image in the array
// Get all the <input> elements
var buttons = document.querySelectorAll(".buttonContainer > input");
// Convert that node list into an array and get the index of the
// one that got clicked (event.target is the one that got clicked)
var index = (Array.prototype.slice.call(buttons)).indexOf(event.target);
// Set the background to the right image from the array
picHolder.style.backgroundImage = "url(" + backgrounds[index] + ")";
}
#photodiv { width:100px; height:100px; border:1px solid grey; background-size:cover; }
<!-- id's are not needed but wrapping all the buttons in a common ancestor will help -->
<div class="buttonContainer">
<input type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
</div>
<div id="photodiv"></div>

you should probably change the way you're doing it :
I will suggest something like this:
document.getElementById("one").addEventListener("click", photo(1));
document.getElementById("two").addEventListener("click", photo(2));
document.getElementById("three").addEventListener("click", photo(3));
document.getElementById("four").addEventListener("click", photo(4));
function photo(x) {
var photograf= document.getElementById("photodiv");
switch (x) {
case 1:
photograf.style.backgroundImage= "url('1.png')";
break;
case 2:
//Statements executed when the
//result of expression matches value2
break;
default:
//Statements executed when none of
//the values match the value of the expression
break;
}
}
SOURCE :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

function photo(e)
{
var photograf= document.getElementById("photodiv");
if(sanitize(e.target.value))
photograf.style.backgroundImage= `url('${e.target.value}.png')`;
}
div id="photodiv">
</div>
<input type="button" value="1" id="one">
<input type="button" value="2" id="two">
<input type="button" value="3" id="three">
<input type="button" value="4" id="four">`

Related

How enable disabled checkbox of a specific div?

Here I'm using firebase to display all driver info one by in one div. I have 6 div(i.e 6 object in driver reference) & each div has a checkbox with enabled/disabled option. I want operate checkbox in such way that if I click checkbox of 1st div it will change in only in 1st div,if I click checkbox of 2nd div it will change in only in 2nd div,& so on but the problem is when I clicked any checkbox only 1st checkbox is change... How can I overcome this...thanks in advance
<script>
function contactHtmlFromObject(Key, Driver){
console.log(Key,Driver);
if(Driver.Gender=='Male'){
html +='<input type="checkbox" id="disablecheckbox" onclick="loaddisable(\''+Key+'\')"><span id="toggle">Enabled</span>';
}
else{
html +='<input type="checkbox" id="disablecheckbox" onclick="loaddisable(\''+Key+'\')" checked><span id="toggle">Disabled</span>';
}
}
function loaddisable(Key) {
var toggle= document.getElementById("toggle");
var dcb= document.getElementById("disablecheckbox");
var Refdis = firebase.database().ref("Driver/"+Key);
Refdis.on("value", function(snapshot) {
if (dcb.checked == true){
toggle.innerHTML="Disabled";
}
else {
toggle.innerHTML="Enabled";
}
});
}
As the nice folks from the comments already suggested, your IDs aren't unique. That's the whole purpose of a ID, right ?! :)
So your JS functions look at the first element with the id, does what it supposed to do with it, and stops.
Instead of using id, I used a class as the selector and built two functions:
One for enabling the checkbox
One for disabling them.
I achieved that simply by looping over the elements that have that specific class name.
Check out the code snippet and see if it works for you ;)
function disable(obj){
const elem = document.getElementsByClassName("checks");
for(let i = 0; i < elem.length; i++){
if(obj != elem[i]){
elem[i].disabled = true;
}
}
}
function enable(obj){
const elem = document.getElementsByClassName("checks");
for(let i = 0; i < elem.length; i++){
if(obj != elem[i]){
elem[i].disabled = false;
}
}
}
Checkbox 1: <input type="checkbox" class="checks"> <br>
Checkbox 2: <input type="checkbox" class="checks"> <br>
Checkbox 3: <input type="checkbox" class="checks"> <br>
Checkbox 4: <input type="checkbox" class="checks"> <br>
Checkbox 5: <input type="checkbox" class="checks"> <br>
<button onclick="disable(this)">Disable All</button>
<button onclick="enable(this)">Enable All</button>

How can I get the value of the radio button after click

How will I get the value of the radio button after clicked on the button?
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
kleuren[i].onclick = function(){
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + this.value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br />
<input type="radio" name="radioGroup" value="blauw" />Blauw</br />
<input type="radio" name="radioGroup" value="geel" />Geel</br />
<input type="radio" name="radioGroup" value="groen" />Groen</br />
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
Now it depends on click on the radio button, but I'd to depend on click on the button
The issue seems to be be the inner click event on the radio button. If you change the loop to an if statement checking if it's checked then you can output the value on the button click:
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
if (kleuren[i].checked === true) {
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + kleuren[i].value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br>
<input type="radio" name="radioGroup" value="blauw" />Blauw</br>
<input type="radio" name="radioGroup" value="geel" />Geel</br>
<input type="radio" name="radioGroup" value="groen" />Groen</br>
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
First of all, please consider using english-named variables, it will improve readability by a lot.
Second of all, line
var kleuren = document.querySelectorAll('input[type=radio');
has a typo, it's missing a closing square bracket - ].
To check a checkbox/radio button value you can use checkbox.checked, where checkbox is your DOM object selected by querySelector.
You're basically already doing it. When you click the button, in the click handler for the button, just grab the radio button element using a selector (either class or id), with a "querySelector" call (just like you're doing). Inspect that element for whatever property makes sense (probably "checked").
Something like:
<button onclick="onClick ()">Click Me</button>
...
onClick () {
const kleuren = document.querySelector ( [mySelectorByIDorClass, etc.] );
console.log ( kleuren.checked );
}
See here:
https://www.w3schools.com/jsref/prop_radio_checked.asp
The checked property will tell you whether the element is selected:
if (document.getElementById('id').checked) {
var variable = document.getElementById('id').value;
}

Hiding and showing html elements with radio button and javascript style=none

I am trying to write a function that will show or hide an html element (contained in a div) using javascript. Right now I have 3 radio buttons (to eventually show/hide 3 elements depending on radio button selected, but right now I am just trying to hide one element (month) if year or week is selected, and to show it if month is selected. My html is:
<div id="setting">
<input type="radio" id="year" name="view" value="year"> year<br>
<input type="radio" id="month" name="view" value="month"> month<br>
<input type="radio" id="week" name="view" value="week"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
My javascript is:
function defineSetting (){
var setting = document.getElementById('setting').checked;
if(setting =='year'){
document.getElementById("cal").style.display = "none";
}else if(setting =='month'){
document.getElementById("cal").style.display = "unset";
}else if(setting =='week'){
document.getElementById("cal").style.display = "none";
}
}
I am also not super experienced with javascript and am trying to figure out how to call the function (if it works). If it is in the document ready function will it run when the page is loaded or do i need to call it somewhere.
I think this is what you're going for. You want to add an event listener to the buttons, and pass the value of the input that's checked to the defineSetting() function that hides/shows your #cal element. I also simplified your test in defineSetting()
<div id="setting">
<input type="radio" id="year" name="view" value="year" class="setting"> year<br>
<input type="radio" id="month" name="view" value="month" class="setting"> month<br>
<input type="radio" id="week" name="view" value="week" class="setting"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
<style>
.hidden { display: none; }
</style>
<script>
var inputs = document.getElementsByClassName('setting'),
setting;
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
el.addEventListener('change', function() {
defineSetting(this.value);
})
}
function defineSetting(setting) {
if (setting == 'year' || setting == 'week') {
document.getElementById("cal").classList.add('hidden');
} else {
document.getElementById("cal").classList.remove('hidden');
}
}
</script>
This will help you out:
How to get value of selected radio button?
You are trying to get the checked value of a div element, but this element doesn't have that. The input element do have that property so that's where you can get it from.

Javascript Radio Button Value in URL

I've read variations on this for a few days and can't find a working solution to what I want. And it's probably easier than I'm making out.
I have a set of radio buttons, and want to pass the checked value to part of a URL.
<input type="radio" name="link" value="one" checked="checked">One
<input type="radio" name="link" value="two">Two
<input type="radio" name="link" value="three">Three
And I want the value of whichever one is checked to be passed to a variable such as
dt which then passes to the Submit button which takes you to a url that includes text from the radio buttons.
<input type="button" value="OK" id="ok_button" onclick="parent.location='/testfolder/' + dt;>
But I'm struggling to find out how to get
var dt = document.getElementByName('link').value;
to work for me when I try and apply a for loop to make sure it's checked.
Does my onclick='parent.location.... in the submit button need to be in a function rather than part of the submit button? So the same function can grab the value of the radio button?
So I'm appealing to StackOverflowers for hopefully a bit of guidance... Thanks
First of you want to know which value your combobox has with this easy to use on-liner.
document.querySelector('[name="link"]:checked').value;
I suggest using event handlers to handle the javascript, so don't write it in the onclick attribute.
var btn = document.getElementById('ok_button');
btn.addEventListener('click', function(){ /*handle validations here*/ })
jsfiddle
you can try below code
<input type="button" value="OK" id="ok_button" onclick="functionName();'>
JavaScript Code
<script type="javascript">
function functionName(){
var radios = document.getElementsByName('link'),
value = '';
for (var i = radios.length; i--;) {
if (radios[i].checked) {
value = radios[i].value;
break;
}
}
window.location.href='/testfolder/'+ value
}
</script>
var dt = document.getElementsByName('link')[0].value works for me
you can use it in either the inline onclick handler or a function you define
<input type="radio" id="1" name="link" onchange="WhatToDo()" value="one">One</input>
<input type="radio" id="2" name="link" onchange="WhatToDo()" value="two">Two</input>
<input type="radio" id="3" name="link" onchange="WhatToDo()" value="three">Three</input>
<script type="text/javascript">
function WhatToDo() {
var rButtons = document.getElementsByName('link');
for (var i = 0; i < rButtons.length; i++) {
if (rButtons[i].checked) {
alert(rButtons[i].value);
}
}
}
</script>
Maybe something like this. Use onchange and then loop through your radio buttons. Whilst looping look to see if the radio button is checked. Its a starting point.

I need to make all buttons disappear when one is clicked

Im writing a game of sorts that presents you with multiple options. Once you choose your option, all buttons, including your selection, should disappear and you move on to the next round. I have a script that allows this to be done, however for each round of buttons I would have to rewrite it to adhere to the new set of buttons. To save from having to repeat myself each time, I'm trying to get a universal script that will accomplish this
HTML
<input type="button" class="btn" id="getUp" name="answer" value="get up" onclick="this.style.display='none'; hideSleepIn(); " />
<input type="button" class="btn" id="sleepIn" name="answer" value="sleep in" onclick="this.style.display='none'; hideGetUp();" />
JavaScript
var hidden = false;
var click = onClick;
function hideSleepIn()
{
hidden = !hidden;
if(getUp === click)
{
document.getElementById('getUp').style.visibility = 'visible';
}
else
{
document.getElementById('sleepIn').style.visibility = 'hidden';
}
}
Try replacing
document.getElementById('getUp').style.visibility = 'visible';
with this
document.getElementById("getUp").style.display = 'none';
I worked the current script I was using to hide the divs, to also hide/ show the buttons on the page
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
<input type="button" class="unhidden" id="firstPath" value="get up" onclick="unhide('getUpText'); unhide('firstPath2'); unhide('firstPath');" />
text
<input type="button" class="unhidden" id="firstPath2" value="sleep in" onclick="unhide('sleepInText'); unhide('firstPath'); unhide('firstPath2');" />
text

Categories