previous button not working - javascript

Hello guys i have creates this code but it's not working in which way i want it to work
i have added some colors here and i want them to come in one by one after i click next button,next button is working propely but when i press previous button it's adding +1 then then go -1 hope you understand what i am trying to ask
thank you
it's only javascript,html and css
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#box{width: 500px; height: 400px; background: #CCC;}
</style>
</head>
<body>
<div id="box"></div>
<input type="button" value="NEXT" onclick="changecolor()">
<input type="button" value="PREVIOUS" onclick="prevcolor()">
<script type="text/javascript">
var boxcolor=["pink","blue","orange","magenta"];
var i=0;
function changecolor(){
var div=document.getElementById('box');
div.style.background=boxcolor[i];
i++;
if(i==boxcolor.length){
i=0;
}
}
function prevcolor(){
var div=document.getElementById('box');
div.style.background=boxcolor[i];
i--;
if(i==boxcolor.length){
i--;
}
}
</script>
</body>
</html>

You first set the color and only then increment/decrement i:
div.style.background=boxcolor[i];
i--;
So when you have this sequence:
i = 0, color=grey (not set yet)
click NEXT
color=pink, i becomes 1
click NEXT
color=blue, i becomes 2
click PREVIOUS
color=orange, i becomes 1
See how i is always set to the next color? So no matter what button you click, the next color is already determined by your previous click.
You can easily catch this type of problem by stepping through your code in a debugger.
Update
Below is a working code snippet that is a bit easier to follow by splitting the increment/decrement from the actual changing of the color.
var boxcolor=["pink","blue","orange","magenta"];
var i=0;
changecolor();
function changecolor(){
var div=document.getElementById('box');
div.style.background=boxcolor[i];
}
function nextcolor() {
i++;
if(i==boxcolor.length){
i=0;
}
changecolor();
}
function prevcolor(){
i--;
if(i==-1){
i = boxcolor.length-1;
}
changecolor();
}
#box{width: 200px; height: 100px; background: #CCC;}
<div id="box"></div>
<input type="button" value="NEXT" onclick="nextcolor()">
<input type="button" value="PREVIOUS" onclick="prevcolor()">

A possible solution could be this one:
Javacsript:
var boxcolor=["pink","blue","orange","magenta"];
var div=document.getElementById('box');
var len = boxcolor.length;
var i=0;
changeColor();
function changeColor(){
div.style.background=boxcolor[i];
}
function nextcolor(){
i = (i+1) % len;
changeColor();
}
function prevcolor(){
i = (len+(i-1)) % len;
changeColor();
}
HTML:
<div id="box"></div>
<input type="button" value="NEXT" onclick="nextcolor()">
<input type="button" value="PREVIOUS" onclick="prevcolor()">
CSS:
#box{
width: 500px; height: 400px;
}
Check this link jsfiddle to see a working example. Hope it's useful!

Related

Making a button that shows a hidden image on click

I've found tutorials that make an image hidden with some css, javascript and html but I'm having trouble making the image hidden first, and then having the button be able to make it visible and then hidden if pressed again.
edit: hopefully this code should help! Again, sorry I can't figure some of this out, I don't really know how this site works and I'm pretty new to coding,,,,
edit 2: I added where the function is being called. It's suppose to be a multiple choice that shows an image when correct!
<style>
div.notdropdown {
margin-top: 100px;
margin-bottom: 100px;
border: 1px solid black;
background-color: rgb(181, 204, 180, 0.9);
}
.hide{
display:none;
}
</style>
</body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<div id="myDIV">
<img class= "hide" src="https://www.merriam-webster.com/assets/mw/static/art/dict/frig_bi.gif">
<br>
<a class= "hide" href="https://www.merriam-webster.com/dictionary/frigate%20bird">https://www.merriam-webster.com/dictionary/frigate%20bird </a>
<br>
</div>
<h1>What is a Frigate?</h1><br>
<form >
<input type="radio" name="choice" value="Bird"> A type of Bird
<input type="radio" name="choice" value="Mangrove"> A type of Mangrove tree
<input type="radio" name="choice" value="Sea Creature"> A type of Sea Creature
<input type="radio" name="choice" value="None"> None of These
</form>
<button onclick="submitAnswer();"> Submit Answer</button>
</body>
<script>
function submitAnswer() {
var radios = document.getElementsByName("choice");
var i = 0, len = radios.length;
var checked = false;
var userAnswer;
for( ; i < len; i++ ) {
if(radios[i].checked) {
checked = true;
userAnswer = radios[i].value;
}
}
if(!checked) {
alert("please select choice answer");
return;
}
// Correct answer
if(userAnswer === "Bird") {
myFunction();
alert("Answer is correct!");
}
// incorrect answer
else {
alert("Answer is wrong!");
}
}
</script>
</body>
</html>
in fact it's very simple, just use the toggle method, which allows you to easily enable and disable a class in an element
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<button onClick="toggleImage()" class="w-100 mb-10">Show/Hide</button>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
to work with a link to just change the tag to a and use href="#"
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<a onClick="toggleImage()" class="w-100 mb-10" href="#">Show/Hide</a>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
You just need to call your function on button tag. Add a button in your html file on which you want your div to toggle. As you are using function name myFunction, call it on that function using
onClick="myFunction()"
And your code should work fine. Don't need to add any new class or even hide your div by default.
check this code. I think this will help you.
<button id = "showhide" onclick = "showhide()">Show Hide Image</button>
<div id = "image" style="width: 100px; height : 100px;">
<h4> Image Code </h4>
</div>
<script>
$('#showhide').on('click', function(e){
$("#image").toggle();
});
</script>

How to include a input in a label in a querySelector() in javascript?

I am trying to construct a personality quiz for my school project. Everything was working fine until I decided that I want the inputs for the radio buttons to be just pictures. The problem is that I am not sure how to save the selected choice and its value, in order to calculate the result.
This is my HTML code:
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<input type="radio" name="colour" class="a" value="-1" />
<label for="p">
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
This is my CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
And this is my Javascript:
function submitSimpleQuiz() {
"use strict";
var colour = praseInt(document.querySelector('input[name = "colour"]:checked').value);
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
} else {
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
This is just one question and answer but essentially all the answers should add up to an outcome which will display a personality description. I don't know why the button for submitting doesn't work anymore.
I would greatly appreciate the help.
I am only new to coding, but I tried including the label into the javascript and also changing the layout of the HTML so that the input is included in the label tag.
As I am sure you won't stop with only 1 question, here is a working snippet in which you can add more questions easily:
function submitSimpleQuiz() {
"use strict";
var total = 0;
var answer = ""; // Added, just because… (see below)
// Easy selection, now! That counts only "selected" inputs!
var inputs = document.querySelectorAll("#simplequiz .selected input");
for (var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if (total < 0) {
answer = "Goth";
} else {
answer = "Minimalistic";
}
// Moved outside of the if to only have these instructions one time
document.getElementById("simplequiz").style.display = "none";
document.getElementById("answer").innerHTML = answer;
}
// Your other code, I haven't touched it. Promise.
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<!-- Modified order -->
<label for="p">
<input type="radio" name="colour" class="a" value="-1" />
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
<!-- Added another one below -->
<label for="p">
<input type="radio" name="colour" class="a" value="1" />
<img src="images/2.jpg" alt="Minimal colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
<!-- Added "answer" -->
<div id="answer"></div>
Anyway, I've got a few remarks, here:
⋅ Your function submitSimpleQuiz is in JavaScript only, whereas your other code is in jQuery. You should choose what you want to use!
⋅ I moved the inputs in your labels to make it easier to select them.
⋅ Why are you using inputs if you're hiding them, and can't/don't check them?!…
Hope it helps.
You need to remove line :
$('#simplequiz input:radio').addClass('input_hidden');
Or you need to modify the line:
var colour = parseInt(document.querySelector('input[name = "colour"]:checked').value);
Because if you uncheck radiobutton you can't get the value. And You have to use parseInt not praseInt. it's an error.
First off all you need to import Jquery for using Jquery function $.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Second it is parseInt not praseInt.
Third:
use this piece of code instead of yours:
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
Fourth:
for your script to work correctly your javasScript should be -
<script type="text/javascript">
function submitSimpleQuiz(){
"use strict";
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
if (document.querySelector("div#simplequiz input[name = 'colour']").checked) {
colour = 0;
}
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
}
else
{
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>

Remove <div> elements created by Javascript by using javascript

My code atm looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
}
init();
</script>
</body>
</html>
So what I want, is for the remove-button to remove the divs that im creating. Ive been googling around and have tried alot of different codes, cant seem to get it to work..
In your specific situation, you have two basic choices:
Just set innerHTML on the element to "":
myFigures.innerHTML = "";
It's slower than some alternatives, but you're not doing this in a tight loop, and it's easy.
Use a loop with removeChild:
while (myFigures.firstChild) {
myFigures.removeChild(myFigures.firstChild);
}
See this other SO answer for information comparing the two techniques.
Here's that first option in context:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
myFigures.innerHTML = "";
}
init();
</script>
</body>
</html>
Like T.J. Crowder said,
myFigures.innerHTML = "";
would work. However, that assumes that myFigures is empty when your DOM is initially loaded. If that is NOT the case, you need to add a class to the div when you create it.
AddDiv function:
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div class='AddedDiv'></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
To remove them:
$(".AddedDiv").each(function(){
$(this).parentNode.removeChild($(this));
});

How can I toggle onClick var div class style without using jQuery?

I am attempting to toggle the height of all elements with class name on button click.
Here is what I am currently using. Right now it will work onClick the first time, but wont change back on second click. When I change if statement to something NOT true, the function still fires.
<head>
<script type="text/javascript">
function changeHeight() {
var elems = document.getElementsByClassName('div1');
for(var i = 0; i < elems.length; i++)
{
if (elems[i].style.height = '25px'){
elems[i].style.height = '110px';
}
else {
elems[i].style.height = '25px';
document.getElementById("expand").innerHTML="[+]";
}
</script>
<style type="text/css">
.div1 {
overflow:hidden;
height:25px;
}
</script>
</head>
<body>
<button type="button" id="expand" onClick="changeHeight();">[+]</button>
<div class="div1">
content
</div>
<div class="div1">
content
</div>
</body>
I believe the issue is I can not get my 'else' to fire because my if is not firing properly.
Any ideas?
Thanks
-Trevor
your if condition check is wrong, you need to use equality operator (==) and not assignment operator ( = ) in condition check, so change:
if (elems[i].style.height = '25px'){
..
to
if (elems[i].style.height == '25px'){ //use == not =
..
and yes the closing tag } of for loop is also missing, do:
for(var i = 0; i < elems.length; i++) {
if (elems[i].style.height == '25px'){
elems[i].style.height = '110px';
}
else {
elems[i].style.height = '25px';
document.getElementById("expand").innerHTML="[+]";
}
}
Use descendant selector for this kind of task. It's much easier.
http://jsfiddle.net/h7vGj/2/
<head>
<style type="text/css">
.div1 {
overflow:hidden;
height:25px;
}
.on .div1 {
height: 110px;
}
</style>
<script>
function foo(ele) {
if ( !ele.state ) {
document.body.className = "on";
ele.state = true;
}
else {
document.body.className = "";
ele.state = false;
}
};
</script>
</head>
<body>
<button type="button" id="expand" onclick="foo(this);">[+]</button>
<div class="div1">
content
</div>
<div class="div1">
content
</div>
</body>
PS. Your style tag is closed by script tag.

Simple image gallery JS

I'm trying to create a simple image gallery with radio buttons. Images are set to Display: none; by default. What I want is for them to display as block when I click on their respective buttons.
<html>
<head>
<style>
.img { width: 250px;
max-height: 300px;
display: none;
}
</style>
<script>
function picture (a) {
var pic = document.getElementById('image')
if (a == 1) {
pic.src="julia1.jpg"
} else { pic.src="julia2.jpg"}
pic.style.display ="block";
}
</script>
</head>
<body>
<img class="img" id="image" src="julia1.jpg">
<form action="">
<input type="radio" onclick="picture(1)" name="picture"></input>
<input type="radio" onclick="picture(2)" name="picture"></input>
</form>
</body>
</html>
On the browser console it says that object is not a function. What does that mean? (thats for both input tags)
The last line should read
pic.style.display = "block";
If anyone looking for simple js gallery check this example :
https://codepen.io/zarokr/pen/ZEzBYvY
let current = document.getElementById('current');
let thumbnails = document.getElementsByClassName('thumb');
for(let i = 0; i<thumbnails.length; i++){
thumbnails[i].addEventListener('click',changeImage);
}
function changeImage(){
let getsrc = this.getAttribute('src');
current.setAttribute('src',getsrc);
}

Categories