Image change with toggle - javascript

Been working on a home automation dashboard and I need some help. How do I get the image to change when the button is toggled ON and OFF. I have a sun svg for on and moon svg for off.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
<!-- Add font from Google fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap" rel="stylesheet">
<!-- Link CSS style sheet to html document -->
<link rel="stylesheet" href="style.css">
<!-- Link JavaScript file to html document -->
<script src="mqttws31.js"></script>
<script src="dashboard.js"></script>
</head>
<body>
<div class="header">
<h1>Home Automation Dashboard</h1>
</div>
<hr>
<div id="messages"></div>
<div id="status"></div>
<hr>
<ul class="dashboard">
<ol class="b">
<li class="dashboard_item kitchen">
<img src="./moon.svg" width="40px" height="40px" alt="">
<h4>Kitchen</h4>
<p id="kitchen-light">OFF</p>
<button id="kitchen-btn">Toggle</button>
</li>
<ol class="b">
<li class="dashboard_item frontdoor" >
<img src="./door-closed.svg" width="40px" height="40px" alt="">
<h4>Front Door</h4>
<p>CLOSED</p>
</li>
</ul>
</body>
</html>
<!-- variable in js -->
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
KitchenState = !KitchenState;
});
Been trying examples online with no luck so far.

Give some id attribute to the image and then change it in the same way like you are changing the innerHTML. For image you just need to change the src accordingly.
<script>
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
document.getElementById('toggle-img').src = KitchenState ? './sun.svg' : './moon.svg'
KitchenState = !KitchenState;
});
</script>
<img src="./moon.svg" width="40px" id="toggle-img" height="40px" alt="">

use .setAttribute or .src
add id kitchen-icon to tag <img> icon
and try code:
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
document.getElementById('kitchen-icon').src = KitchenState ? './moon.svg' : './sun.svg'
KitchenState = !KitchenState;
})

From the point of view of your question, I think you need the following code
let btnAll = document.getElementByTagName('button')
let conAll = document.getElementByClassName('content')
let btnAllLen = btnAll.length
//Create a callback function for the click event of each button
for (let i = 0; i < btnAllLen; i++) {
!(function(n) { // Register click events
btnAll[n].addEventListener('click', function() {
for (let j = 0; j < btnAlllen; j++) {
btn[j].className = ""
conAll[j].style.display = "none"
}
this.className = "active"
conAll[n].style.display = "block"
})
})(i)
}
.main {
text-align: center;
}
button:focus {
outline: none;
}
nav {
margin-top: 30px;
box-sizing: border-box;
}
button {
background: white;
border: none;
height: 36px;
line-height: 36px;
width: 80px;
text-align: center;
border: 1px solid lightgray;
border-radius: 4px;
cursor: pointer;
}
nav>button:not(:first-child) {
margin-left: 15px;
}
.active {
background: black;
color: white;
}
.content {
margin-top: 40px;
}
.content>p {
display: none;
}
<div class="main">
<nav>
<button class="active">content 1</button>
<button>content 2</button>
<button>content 3</button>
<button>content 4</button>
</nav>
<div class="content">
<p style="display: block;">content1</p>
<p>content2</p>
<p>content3</p>
<p>content4</p>
</div>
</div>

Related

how do i open modal with javascript. without using jquery

How do I make a modal visible with javascript? I don't want to do it using jquery. i just want it with javascript. And I don't want it to open when I click a button. I want it to be opened as a result of some operations in javascript. I made it with modal bootstrap. my codes are below.
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="modal fade" tabindex="-1" id="sonucModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Test Durumu</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="durum"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Çıkış</button>
<button type="button" class="btn btn-primary">2. Aşamaya Geç</button>
</div>
</div>
</div>
</div>
<div class="container" style="height: 100vh;">
<div class="row" style="height: 100vh;">
<div class="col-md-12 d-flex justify-content-center" style="height: 400px;">
<div class="card" style="width: 25rem; margin-top:20vh; ">
<div class="card-body" style="text-align: center;">
<h5 class="card-title text-primary">Soru</h5>
<span class="text-black-50 fs-5" id="soru"></span>
<input class="w-100 form-control mt-4" type="text" id="cevap"/>
<button class="btn btn-outline-primary mt-4 w-100" id="ok">Tamam</button>
</div>
<ul class="list-group list-group-flush">
<li id="anaCan" class="list-group-item fw-bold">Kalan Can: <span id="can"></span></li>
</ul>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
javascript code:
var turkceCumleler = [
"Merhaba",
"İyi Sabahlar",
"İyi Günler",
"İyi Akşamlar",
"İyi Geceler",
"Tekrar Görüşmek Üzere(Yüz yüze)",
"Tekrar Görüşmek Üzere(Tel.)",
"Yakında Görüşürüz",
"Güle Güle"
];
var almancaCumleler = [
"hallo",
"guten morgen",
"guten tag",
"guten abend",
"gute nacht",
"auf wiedersehen",
"auf wiederhögen",
"bis bald",
"tschüss"
]
var sayilar = [];
var healt = 3;
const getQuestion = () =>{
document.getElementById('can').textContent=healt;
let rastgele = Math.floor(Math.random()*turkceCumleler.length);
if(sayilar.indexOf(rastgele) === -1){
sayilar.push(rastgele)
document.getElementById('soru').textContent = turkceCumleler[rastgele];
document.getElementById('cevap').value = ""
}else{
getQuestion();
}
if(sayilar.length === turkceCumleler.length){
//here i want modal to open
}
}
const compareQuestionAnswer = () =>{
if(document.getElementById('cevap').value === ''){
alert("boş geçilemez")
}else{
let deger = almancaCumleler.indexOf(document.getElementById('cevap').value.toLowerCase());
if(deger === -1){
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}else{
let deger1 = turkceCumleler.indexOf(document.getElementById('soru').textContent);
if(deger === deger1){
getQuestion();
}else{
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}
}
}
}
window.onload = getQuestion;
document.getElementById('ok').addEventListener('click',compareQuestionAnswer);
document.getElementById('anaCan').style.color='green';
Bootstrap depends on jQuery, and you're already including jQuery in your code.
But if you want to create a modal without Bootstrap and jQuery, you can do so with CSS and JavaScript. Use an event listener to listen for whatever JavaScript event you desire, then show the modal when that event occurs.
Here is a simple example:
// Show the modal when you hover over the red box
trigger.onmouseover = () => {
modal.style.display = "block";
}
// Hide the modal when you click the close button
document.getElementsByClassName("close")[0].onclick = () => {
modal.style.display = "none";
}
// Hide the modal if you click outside of the modal area
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
}
#trigger {
height: 100px;
width: 100px;
background-color: red;
}
.modal {
display: none; /* Hidden Initially */
position: fixed;
z-index: 1; /* Higher Z-Index To Sit On Top */
left: 0;
top: 0;
width: 100%; /* Full Width */
height: 100%; /* Full Height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div id="modal" class="modal">
<!-- Modal Content -->
<div class="modal-content">
<span class="close">x</span>
<p>Modal content here</p>
</div>
</div>
<div id="trigger">
Move mouse into this box to trigger modal.
</div>
You just need to declare a new modal object, like:
const sonucModal= document.getElementById('sonucModal');
const modalEl = new bootstrap.Modal(sonucModal);
and then call it like this whenever you need to open it:
modalEl.show();
Here is a JSFiddle for reference, the modal opens automatically after 2 seconds.

How to blur the whole body except a list item?

I wanted to create an effect where the whole body gets blurred or dimmed and only a particular list item appears clear. However when I set the z-index to the list item, it doesn't work. And when I set the z-index of the whole un-ordered list, it works but the all the list items appear clear (which I don't want).
Let me show you my html code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ashish Toppo</title>
<link href="https://fonts.googleapis.com/css?family=Oxanium&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body >
<!-- the html for the top bar starts here -->
<div class="top_bar" id="topBar">
<div class="logo_name" id="logoName">Ashish Toppo</div>
<ul class="menu">
<li class="menu_items currently_active_menuItem" id="home">home</li>
<li class="menu_items" id="about">about</li>
<li class="menu_items" id="education">education</li>
</ul>
</div>
<!-- the html for the top bar ends here -->
<!-- the html for the intro starts here -->
<div class="intro" id="intro">
<div class="profile_pic" id="profilePic">
<img id="profileImg" src="images/ashish-toppo-green.jpg" width="100%" height="100%" alt="a picture of mine">
</div>
<div class="intro_box" id="introBox">
<!-- some introduction text here -->
<center id="aboutPointer">To know more about me, go to the about section!</center>
</div>
</div>
<!-- the html for the intro ends here -->
<script src="js/uiversal.js"></script>
<script src="js/index.js"></script>
</body>
</html>
Now, the Universal javaScript file:
/* this is a reusable js file universal to all web pages */
/* Ashish Toppo */
"use strict";
function get(id_or_class){
var obj = {
element: ( document.getElementById(id_or_class) ) ? document.getElementById(id_or_class) :
( document.getElementsByClassName(id_or_class) ) ? document.getElementsByClassName(id_or_class) :
( document.querySelector(id_or_class) ) ? document.querySelector(id_or_class) :
console.error("The provided HTML element could not be found"),
html: () => { return obj.element; },
changeText: (text) => { obj.html().innerHTML = text; },
appendText: (text) => {
let appendOn = obj.html().innerHTML;
obj.html().innerHTML = appendOn + text;
},
previousDisplayMode: "block",
hide: () => {
obj.previousDisplayMode = obj.html().style.display;
obj.html().style.display = "none";
},
show: () => {
obj.html().style.display = obj.previousDisplayMode;
},
on: (event, callBack) => {
obj.html().addEventListener(event, callBack);
},
previousZIndex: 1,
focusOn: () => {
let blur = document.createElement("div");
blur.className = "theDivThatBlurs";
blur.style.width ="100vw";
blur.style.height ="100vh";
blur.style.display ="block";
blur.style.position ="fixed";
blur.style.top ="0";
blur.style.left ="0";
blur.style.zIndex ="9";
blur.style.backgroundColor ="rgba(0, 0, 0, 0.9)";
blur.innerHTML = "";
document.body.appendChild(blur);
obj.html().style.zIndex = "100";
}
}
return obj;
}
and the index.js file was as followed:
/* my css wasn't working as i wanted, so i had to fix it using js */
"use strict";
(function(d){
const active = d.getElementsByClassName("currently_active_menuItem");
active[0].style.textDecoration = "none";
})(document);
var about = get("about");
var aboutPointer = get("aboutPointer");
aboutPointer.on("click", function(){
console.log("the about pointer has been clicked");
focus(about);
});
function focus(theElement){
console.log("the focus is working");
theElement.focusOn();
}
You can use the box-shadow property to achieve the dimming effect. Quick and easy :)
Just toggle a class programmatically and it should work for any element you have.
Code
function focusAndDim() {
document.getElementById("maindiv").classList.toggle("visible");
// if you want to get more fancy ;)
document.getElementsByTagName("body")[0].classList.toggle("blur");
}
.visible {
box-shadow: 0 0 0 10000px #ccc;
/* this code below make everything else hidden */
/* box-shadow: 0 0 0 10000px #fff; */
position: relative;
}
.btn {
height: 20px;
line-height: 1.4;
border: 2px solid #999;
padding: 12px 24px;
margin-bottom: 10px;
border-radius: 2px;
cursor: pointer;
}
body {
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
height: 100vh;
}
body.blur div {
filter: blur(2px);
}
body.blur div.visible {
filter: blur(0);
}
<div class="btn" onclick="focusAndDim()" id="maindiv">Click Me</div>
<div>Other elements</div>

Problem with image 'rotations' within a div element

I'm using the code below to create a 'rotation' of images for display on a website. I wish for the images to display within a 'div' element...and i'm having trouble accomplishing that. It seems the problem is when I attempt to set each image as the 'background image' for the element (the line that reads "document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";). Only the initial image displays, without any 'rotation' of other images. Any help appreciated, this is becoming very frustrating.
<!DOCTYPE html>
<html>
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
div.rotation {
height: 256px;
width: 100%;
padding: 0px;
background-color: powderblue;
border-style: solid;
border-width: 5px;
border-radius: 25px;
}
</style>
</head>
<body>
<div class="w3-quarter">
<div class="w3-padding-small">
<div class="w3-center">
<div class="rotation">
<p>
<img src='images/rotation/LA_Panel.png' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/McCulloch_256.png' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/MO_Panel.png' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/Rommel.png' id='rotateImg3' style='display:none;' alt='image rotation' />
</p>
</div>
</div>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
var rotation = function () {
var currentImage,
images = [],
ImgName = [],
count,
hideImages,
showImage,
fn;
count = (function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString())) {
images[x] = document.getElementById('rotateImg' + x.toString());
ImgName[x] = document.getElementById('rotateImg' + x.toString()).src;
x++;
}
return images.length;
})();
hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
images[i].style.display = 'none';
}
};
showImage = function (number) {
document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";
images[number].style.display = 'block';
};
fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval(rotation.advanceRotation, 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
};
return fn;
} ();
rotation.setupRotation();
</script>
One thought might be to pluck off the first child and slam him to the end of the line.
let images = document.querySelector('#images');
setInterval(() => {
let el = images.removeChild(images.childNodes[0]);
images.appendChild(el);
}, 1000);
#images {
font-size: 0;
}
.img {
display: inline-block;
width: 30px;
height: 30px;
}
<div id="images">
<div class="img" style="background-color: red"></div>
<div class="img" style="background-color: orange"></div>
<div class="img" style="background-color: yellow"></div>
<div class="img" style="background-color: green"></div>
<div class="img" style="background-color: blue"></div>
</div>

Fruit ninja type game in javascript

I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>

Toggle divs to display mutiple information boxes using buttons on the nav bar

Here is what I have now...
$("#contact").click(function() {
if ( $( "#contact_div" ).length ) {
$("#contact_div").remove();
} else {
var html='<div id="contact_div" class="contact-info"><p>Contact info</p></div>';
$('body').append(html);
}
});
$("#submission").click(function() {
if ( $( "#submission_div" ).length ) {
$("#submission_div").remove();
} else {
var html='<div id="submission_div" class="submission-methods"><p>submission methods</p></div>';
$('body').append(html);
}
});
$("#database").click(function() {
if ( $( "#database_div" ).length ) {
$("#database_div").remove();
} else {
var html='';
$('body').append(html);
}
});
$("#frequent").click(function() {
if ( $( "#frequent_div" ).length ) {
$("#frequent_div").remove();
} else {
var html='<div id="frequent_div" class="Freqeuent kick-codes"><p>frequent kick codes</p></div>';
$('body').append(html);
}
});
#charset "utf-8";
/* CSS Document */
body {
padding: 0px;
margin: 0px;
background-image: url("images/mark-athena-2.png");
background-color: #d4d4d4;
}
a {
text-decoration: none;
font-family: "blessed-facit-semibold", "arial Black", Arial;
color: #999999;
font-size: 12px;
padding: 14px;
}
nav {
background-color: #514a79;
height: 25px;
}
a:hover {
color:#e3e3f2;
}
/* color for link= #e3e3f2 */
div {
height: 100px;
width 150px;
border: solid 1px;
margin: 20px;
overflow: hidden;
background-color: #e6e6e6;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Accelorator</title>
<link rel="stylesheet" href="CSS/accel-stylesheet.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.js"></script>
<script type="text/javascript" src="js/cont.js"></script>
</head>
<body>
<nav>
Home
<a id="contact" href="#">Contact info</a>
<a id="submission" href="#">Submission methods</a>
<a id="database" href="#">Data base</a>
<a id="frequent" href="#">Frequent kick codes</a>
</nav>
<div id="contact_div" class="contact-info">
<p>Contact info</p>
</div>
<div id="submission_div" class="submission-methods">
<p>submission methods</p>
</div>
<div id="frequent_div" class="Freqeuent kick-codes">
<p>frequent kick codes</p>
</div>
</body>
</html>
Okay So when I click "Contact Info" on the Nav bar I want the "contact info div" to display or disappear or toggle... same for Submission methods, Data base, and Frequent kick codes. the divs should be able to be toggled to display information inside, and stay displayed until toggled off by the button that toggled them on...
So here is my HTML Code i have created for this project...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Accelorator</title>
<link rel="stylesheet" href="CSS/accel-stylesheet.css">
</head>
<body>
<nav>
Home
Contact info
Submission methods
Data base
Frequent kick codes
</nav>
<div class="contact-info">
<p>Contact info</p>
</div>
<div class="submission-methods">
<p>submission methods</p>
</div>
<div class="Freqeuent kick-codes">
<p>frequent kick codes</p>
</div>
</body>
</html>
And here is my css
#charset "utf-8";
/* CSS Document */
body {
padding: 0px;
margin: 0px;
background-color: #d4d4d4;
}
a {
text-decoration: none;
font-family: "blessed-facit-semibold", "arial Black", Arial;
color: #999999;
font-size: 12px;
padding: 14px;
}
nav {
background-color: #514a79;
height: 25px;
}
a:hover {
color:#e3e3f2;
}
/* color for link= #e3e3f2 */
div {
height: 100px;
width 150px;
border: solid 1px;
margin: 20px;
overflow: hidden;
background-color: #e6e6e6;
}
You could use jQuery .toggle function, documentation and samples are available here.
You can give an 'id' to the individual navigation anchors, and associate a click event that with jQuery will toggle the div you want. I'd use id in all of them, but you can surely work with class too.
The sample code becomes some like:
<body>
<nav>
Home
<a id="contact" href="#">Contact info</a>
<a id="submission" href="#">Submission methods</a>
<a id="database" href="#">Data base</a>
<a id="frequent" href="#">Frequent kick codes</a>
</nav>
<div id="contact_div" class="contact-info">
<p>Contact info</p>
</div>
<div id="submission_div" class="submission-methods">
<p>submission methods</p>
</div>
<div id="frequent_div" class="Freqeuent kick-codes">
<p>frequent kick codes</p>
</div>
</body>
The jQuery/javascript code looks like:
$("#contact").click(function(){
$("#contact_div").toggle();
});
$("#submission").click(function(){
$("#submission_div").toggle();
});
$("#database").click(function(){
$("#database_div").toggle();
});
$("#frequent").click(function(){
$("#frequent_div").toggle();
});
Two notes:
1. the database section is missing in the original post
2. you need to include the jQuery on the page, either you
load it locally on your server, or include it via CDN, like:
<script src="https://code.jquery.com/jquery-2.2.0.js"></script>
For the second request on this, the code blocks would to be added/removed based on clicks. The jQuery method change, and for the full working solution you also need to correctly both import jquery, source the javascript code, and have an document.ready handler that will actually initialize the elements. The code looks like this (css remains unchanged).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Accelorator</title>
<link rel="stylesheet" href="CSS/accel-stylesheet.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.js"></script>
<script type="text/javascript" src="js/cont.js"></script>
<script>
$( document ).ready(function() {
initialize();
});
</script>
</head>
<body>
<nav>
Home
<a id="contact" href="#">Contact info</a>
<a id="submission" href="#">Submission methods</a>
<a id="database" href="#">Data base</a>
<a id="frequent" href="#">Frequent kick codes</a>
</nav>
<div id="contact_div" class="contact-info">
<p>Contact info</p>
</div>
<div id="submission_div" class="submission-methods">
<p>submission methods</p>
</div>
<div id="frequent_div" class="Freqeuent kick-codes">
<p>frequent kick codes</p>
</div>
</body>
</html>
with the js/cont.js as:
function initialize() {
$("#contact").click(function() {
if ( $( "#contact_div" ).length ) {
$("#contact_div").remove();
} else {
var html='<div id="contact_div" class="contact-info"><p>Contact info</p></div>';
$('body').append(html);
}
});
$("#submission").click(function() {
if ( $( "#submission_div" ).length ) {
$("#submission_div").remove();
} else {
var html='<div id="submission_div" class="submission-methods"><p>submission methods</p></div>';
$('body').append(html);
}
});
$("#database").click(function() {
if ( $( "#database_div" ).length ) {
$("#database_div").remove();
} else {
var html='';
$('body').append(html);
}
});
$("#frequent").click(function() {
if ( $( "#frequent_div" ).length ) {
$("#frequent_div").remove();
} else {
var html='<div id="frequent_div" class="Freqeuent kick-codes"><p>frequent kick codes</p></div>';
$('body').append(html);
}
});
}
You can do this like this:
Html
<nav>
Home
Contact info
Submission methods
Data base
Frequent kick codes
</nav>
<div class="contact-info" data-container>
<p>Contact info</p>
</div>
<div class="submission-methods" data-container>
<p>submission methods</p>
</div>
<div class="frequent-kick-codes" data-container>
<p>frequent kick codes</p>
</div>
Jquery
$(document).ready(function() {
// initially don't show anything
$('*[data-container]').hide();
// Hide or show the div for that menu item. We don't hide the others because that wasn't asked.
$('*[data-container-class]').click(function(e) {
var className = $(this).data('container-class');
$('.' + className).toggle();
});
});
Jsfiddle example here

Categories