How to display/hide a div in another html page - javascript

I have two html pages (produse.html and item.html) and a menu in one of them. When I click a link from the menu I need to go to the other page and in the same time display a specific div and hide the original one from item.html.
I tried it with javascript using onclick method, but it doesn't work. I think the problem is that the javascript code can't get the class name of a div that is in another page.
Can there be something done?
This is the code that I tried.
produse.html
<div class="sideMenu">
prod 1
prod 2
prod 3
prod 4
</div>
item.html
<div class="displayBox yes">
1
</div>
<div class="displayBox">
2
</div>
<div class="displayBox">
3
</div>
<div class="displayBox">
4
</div>
javascript
var prevN = 0;
function displayTheBox(n){
var products = document.getElementsByClassName("displayBox");
products[prevN].className = products[prevN].className.replace(" yes", "");
products[n].className += " yes";
prevN = n;
}
css
.displayBox{
float: left;
height: 200px;
overflow: auto;
position: relative;
box-shadow: 1px 1px 4px 2px #9b9b9b;
background-color: #bbe5f8;
border-radius: 6px;
width: 995px;
margin: 0 0 0 235px;
display: none;
}
.yes{
display: block;
}

JS is a client-side script and it's variables are reset on page load. You can either pass the values by passing as GET parameters or by saving and retriving persistent data using localStorage or cookies.
Here is a simple js function to get GET variables and process function.
function findGetParameter(parameterName) { // Gets the GET variables
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
if(findGetParameter("item")) { // Check if parameter matches
displayTheBox(findGetParameter("item"));
}
var prevN = 0;
function displayTheBox(n) {
var products = document.getElementsByClassName("displayBox");
products[prevN].className = products[prevN].className.replace(" yes", "");
products[n].className += " yes";
prevN = n;
}
Change your hyperlinks to
<div class="sideMenu">
prod 1
prod 2
prod 3
<a href="item.html?item=3">prod 4<a>
</div>
For more info on storage methods, check this SO question What is the difference between localStorage, sessionStorage, session and cookies?
For a good example on js session storage, check this answer to a SO question here https://stackoverflow.com/a/49805713/6060602

Actually, when you're making a function call in a page, it can't be reflected in another one. You've to use backend for that job. But as per your problem is concerned, you may use a language like PHP for doing this job.
Otherwise, you can make a function call at the beginning when the new page is opened.
like,
window.onload()
or jQuery may also be helpful in this case,
$(document).ready(function() { /* code here */ });

That is impossible through normal click events like that.
Two pages will need to interact and since requests are stateless, everything that belongs to one page only really lives in there and nowhere else.
So to perform that, you will need to pass the communication through the request object.
Options:
First - Either create a form line this:
<form action="targetPage" method="get">
<input type="hidden" value="hideSomething" />
<button></button>
</div>
Then inside your TargetPage, retrience the query string from the URL, FInd out more about this here
Second - Either you're not sure if that is the right approach you want to take. Look closer into what you're trying to achieve and see if it's really necessary. I am not sure why you're trying to put those buttons( sideMenu ) on their own page seperate from where the boxes you're trying to control are.

Related

How to create many divs without actually creating them individually

I'm working on a project with html, css and js and I want to create many divs (let's say, 200) so, how can i create them without actually writing code for 200 different divs... I know I can do it with js but could I do it only with html and css..?
As I already said in my comment, you can't do it without JavaScript.
A JavaScript solution would be the following:
const container = document.getElementById("container");
for (let i = 0; i < 200; i++) {
const item = document.createElement("div");
item.classList.add("item", "item-" + i);
container.appendChild(item);
}
#container {
border: 1px solid red;
padding: .5rem;
}
.item {
border: 1px solid black;
height: 3rem;
margin-bottom: .3rem;
}
<div id="container">
</div>
One way with js:
you can create one HTML Span Element and with js you change the content of it. I bet with that knowledge you find something
how it's going? Html or css is not a programming language. So you can't do some kind of automation or repeating code or something like that. The only way to do that sort of things is using Javascript. Here is how:
<div class="container">
<!-- let's say we trying to add divs here. -->
</div>
And here's script:
function addMultiple (where, what, count, callBack) {
for (let i = 0; i < count; i++) {
// creating elements with document.createElement() method
let item = document.createElement(what)
// and then adding them into "where" element.
where.appendChild(item)
/*
and finally we'll have a function called Callback.
This is just gonna take our item as an argument and
do some stuff on it according to what we want.
(I'll show a simple usage down below)
*/
callBack(item)
}
}
// let's say we want to add 200 divs into "container" element
// and then we want to add class name to those divs.
const container = document.querySelector('.container')
addMultiple(container, 'div', 200, item => {
// this code will be repeated for all divs.
item.classList.add('what_ever_you_want')
})

how do i put pics in classlist.remove/add in JS

Im new to stackoverflow and i started learning js just few weeks ago, heres the code:
'use strict';
let a = 1;
king.addEventListener('click', function(){
a++;
if(a%2 == 0){
king.classList.remove(?)
king.classList.add(?)
}
else {
king.classList.remove(?)
king.classList.add(?)
}
});
a -> counter, king is a div, i have two pics named king0 and king1 in pics folder.
Task = when king is clicked, it switches to the second pic, -> first pic and so on
question = how do i put pics in "?", although probably i may did everything wrong and have to start all over
well html was requested but its a very basic one:
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>DOC</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id = "king" class = "kingcss"> //kingcss class is empty
<img src= "pics/king0.png"> </div>
<script src="script.js"></script>
</body>
</html>
classList doesn't contain your images directly; instead it's a list of CSS class names applied to the element. You can associate images with those classes in CSS:
let a = 0;
let king = document.querySelector('.king')
king.addEventListener('click', function() {
a++;
if (a % 2 == 0) {
king.classList.add('one')
king.classList.remove('two')
} else {
king.classList.add('two')
king.classList.remove('one')
}
});
.king {
width: 100px;
height: 100px;
border: 2px solid;
}
.one {
background-image: url('http://placekitten.com/101/101')
}
.two {
background-image: url('//placekitten.com/100/100')
}
<div class="king">King</div>
I'm going to suggest a few simplifications you could make to your code beyond just getting it working though:
You're depending on a global variable a here to keep track of which image you want to switch to next. This isn't necessary, and gives you one more thing to keep track of -- instead it'd be better to just check the element's current state.
You toggle one class on and another class off, which means you actually have four possible states (first one on, second one on, both on, or both off) if things don't go perfectly. (You can actually see this in the above example; before the user clicks it's in the "both off" state). You really only want two possible states: image one, or image two.
Below is an example with those issues resolved: instead of testing a you test the classList contents; and instead of having multiple classes to toggle, one of the images is in the "default" state.
let king = document.querySelector('.king')
king.addEventListener('click', function() {
king.classList.toggle('two')
});
.king {
width: 100px;
height: 100px;
border: 2px solid;
background-image: url('http://placekitten.com/101/101')
}
.two {
background-image: url('//placekitten.com/100/100')
}
<div class="king">King</div>
Please add your HTML. Not everything is wrong. W/o looking at your HTML, I'm assuming you have a different image tag for king0 and king1. If you want to use classList.remove() or classList.add(), you have to specify the class name you are adding or removing from the classList node.

Toggle many classes

so thanks for you all that help me. You made me think what i was doing, so i short my code in what i thought would be good, but before the code was long but working now, short but not works with the first panel even that there is no errors.So maybe a loop?
So the html goes like this:
<div class="container">
<div class="down sound">
<img id="batman" class="image-1-panel active" src="flash.svg">
<img class="image-2-panel notactive" src="http://cdn.playbuzz.com/cdn/3c096341-2a6c-4ae6-bb76-3973445cfbcf/6b938520-4962-403a-9ce3-7bf298918cad.jpg">
<p class="image-3-panel notactive">Bane</p>
<p>Joker</p>
<p>Alfred</p>
</div>
And then it repeats for 3 more containers like that one. On css for the active and not active i have:
.notactive{
visibility: hidden;
position: relative;
}
.active{
position: absolute;
}
And in js:
document.querySelector('#batman').addEventListener('click', batman);
function batman(){
document.querySelector('.image-1-panel').classList.toggle('.notactive');
document.querySelector('.image-1-panel').classList.toggle('.active');
document.querySelector('.image-2-panel').classList.toggle('.active');
document.querySelector('.image-2-panel').classList.toggle('.notactive');
}
But nothing happens... I also have a for loop for sounds that is working still good, but the panels don´t move. Can someone share some light here? I thought in a loop and try it following the function but also didn´t work so clearly I am missing something, maybe wrong element I am trying to catch?
Above i have my question without the edit where you can understand what i mean.
Thanks for your help
I have 4 panels. In each panel, there will be 3 images/text one beyond the other. So it will work that when I press panel 1, panel 2,3 and 4 will turn to show an image. Press panel 2, and panel 1,3 and 4 will turn to show different image then when pressed the panel one. And so one for the rest of the panels.
So i start and i create a function for the first panel. It works, but there is any way i can make it simple? Here is the code:
function guessWho(){
document.querySelector('.image-1-panel').classList.toggle('notactive');
document.querySelector('.image-1-panel').classList.toggle('active');
document.querySelector('.image-2-panel').classList.toggle('active');
document.querySelector('.image-2-panel').classList.toggle('notactive');
document.querySelector('.image-3-panel').classList.toggle('active');
document.querySelector('.image-3-panel').classList.toggle('notactive');
document.querySelector('.image-4-panel').classList.toggle('active');
document.querySelector('.image-4-panel').classList.toggle('notactive1');
document.querySelector('.image-5-panel').classList.toggle('active');
document.querySelector('.image-5-panel').classList.toggle('notactive');
document.querySelector('.image-6-panel').classList.toggle('active');
document.querySelector('.image-6-panel').classList.toggle('notactive2');
document.querySelector('.image-7-panel').classList.toggle('active');
document.querySelector('.image-7-panel').classList.toggle('notactive');
document.querySelector('.image-8-panel').classList.toggle('active');
document.querySelector('.image-8-panel').classList.toggle('notactive3');
}
Any way I can put this simple? I don´t want to use any framework, so it has to be pure js. Thank you
Use a loop.
for (var i = 0; i <= 8; i++) {
document.querySelector(`.image-${i}-panel`).classList.toggle('notactive');
document.querySelector(`.image-${i}-panel`).classList.toggle('active');
}
Given that querySelector takes a string, you could build that string up inside of a loop and use the iterator inside of the string. Something like
for(i = 1; i <= 8; i++) {
document.querySelector('.image-' + i + '-panel').classList.toggle('notactive');
}
would toggle the 'notactive' class for everything that has image-x-panel.
Solution 1
for (var i = 1; i <= 8; i++) {
document.querySelector(`.image-${i}-panel`).classList.toggle('notactive');
document.querySelector(`.image-${i}-panel`).classList.toggle('active');
}
Solution 2
Add some CSS class to your HTML like CLASSNAME
And use try this
document.querySelector(`CLASSNAME`).classList.toggle('notactive');
document.querySelector(`CLASSNAME`).classList.toggle('active');
You can create a list of the new states you want your classes to be modified by. In this case, you have an object that looks like this:
{a:false,i:""}
where a is whether it's active, and i is your post class increment, like "notactive2".
Then you create a nested loop where you iterate over each number twice, and check the position in your list of states to determine what things will be added to your base "active" class.
var activeClassesList = [{a:false,i:""},{a:true,i:""},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:"1"},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:"2"},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:"3"}];
var imageClassPrefix = ".image-";
var imageClassPostfix = "-panel";
var start =1;
var base = 8;
for (var i=0;i<2;i++)
{
var count = 1;
for (var j=start;j<(start+base);j++) {
var modifier = activeClassesList[j-1];
var cls = (modifier.a ? "" : "not") + "active" + modifier.i;
document.querySelector(imageClassPrefix + String(count) + imageClassPostfix).classList.toggle(cls);
count++;
}
start = start + base;
}
Another approach might be to just focus on the results, so we can remove the first selectors for each image panel since they are immediately being overwritten.
That leaves the second queries for each selector. This can be simplified by combining multiple selectors inside a queryselectorAll for items with the same class being toggled.
function guessWho(){
document.querySelector('.image-1-panel').classList.toggle('active');
document.querySelector('.image-2-panel').classList.toggle('notactive');
document.querySelectorAll('.image-3-panel, .image-5-panel, .image-7-panel, .image-7-panel').forEach((f)=>{f.classList.toggle('notactive');})
document.querySelector('.image-4-panel').classList.toggle('notactive1');
document.querySelector('.image-6-panel').classList.toggle('notactive2');
}
guessWho();
.allpanels > div {display: inline-block;border:solid 1px black;height:50px;width:50px;margin:8px;}
.active { background-color:red;}
.notactive { background-color:lightsteelblue;}
.notactive1 { background-color:green;}
.notactive2 { background-color:orange;}
<div class="allpanels">
<div class="image-1-panel">1</div>
<div class="image-2-panel">2</div>
<div class="image-3-panel">3</div>
<div class="image-4-panel">4</div>
<div class="image-5-panel">5</div>
<div class="image-6-panel">6</div>
<div class="image-7-panel">7</div>
</div>

How to rotate HTML content so that the order changes every 30 seconds with jQuery?

Basically i have created a single one column which holds 3 articles, i have given all the articles id's i.e news1,news2,news3 and added content to each accordingly [text and img,plus header]
What i am attempting to do is move the content of
article 1 to the location of article 2
article 2 to the location of article 3
article 3 to the location of article 1
with the articles changing location, every 30 seconds,[the above loop] i have tried appendTo,yesterday thought about fadeout, fadein, using a slide i persume would be; going a little over board in terms of code i think, then again on seconds thought..hmmm
i would rather change the content as one lot than, in parts, i.e headers, paragraphs, images etc.
this is how i started, the idea is if i can get it to work in one pair the rest would, straight forward, to do, be it copy and paste, with a edit of selectors.
setInterval(function(){
var x = getElementById("#news1");
(this).appendTo("#news3");
}, 30000);
Hopefully someone can steer me in the right direction, either by illustrating an example or an event 'action' to check out that might do the trick
Have you ever heard of the DOM manipulation, are those methods form Node reference https://developer.mozilla.org/en-US/docs/Web/API/Node that handles nodes like insertBefore, removeChild, appendChild an so on
For example the folowing uses standard dom manip. to shift the last element to first position in the tree stack. Read the comments for explanations:
// cache the container element
var containerEl = document.getElementById('container');
// This is a live reference to the child node finds the last child.
// The querySelector was use here in order to get a controll over
// what elements category should be manipulated
var lastEl = containerEl.querySelector('.article:last-child');
// move the element in front - remove from parent
containerEl.removeChild(lastEl);
// attach it back in the front.
containerEl.insertBefore(lastEl, containerEl.firstChild);
Now the second part of your problem is the timed event. you can use either requestAnimationFrame or a timer or a interval.
I personalty prefer the timer solution since is retro-compatible and it has no chance of executing the scheduled code simultaneous and you can stop the chaning internally without having a reference to the timerId. Maybe requestAnimationFrame is a better option, but that is up to you.
To chain schedule the executions a simple recursion does the trick:
var timerIdx;
var chainInterval = 6000; // in millis
var callback = function (){
// the execution code here;
timerIdx = setTimeout(callback, chainInterval);
};
to start it you just call :
callback();
to stop it you just call :
clearTimeout(timerIdx);
Now lets put everything together, the style is just for showcasing:
// cache the container element
var containerEl = document.getElementById('container');
var timerIdx;
var chainInterval = 1000; // in millis
var chainRotate = function (){
rotateChildElements(containerEl, '.article')
timerIdx = setTimeout(chainRotate, chainInterval);
};
var rotateChildElements = function(containerEl, childClassName){
// This is a live reference to the child node
var lastEl = containerEl.querySelector(childClassName+':last-child');
// move the element in front
containerEl.removeChild(lastEl);
containerEl.insertBefore(lastEl, containerEl.firstChild);
};
// Start
chainRotate();
var rotateBtn = document.getElementById('rotateBtn');
rotateBtn.addEventListener('click', function(ev){
if (timerIdx !== null){
ev.target.innerHTML = "Start Rotate";
clearTimeout(timerIdx);
timerIdx = null;
} else {
ev.target.innerHTML = "Stop Rotate";
chainRotate();
}
});
* {
box-sizing : border-box;
}
#container {
position: relative;
margin-left : auto;
margin-right: auto;
padding : 8px;
border : 1px dashed magenta;
max-width : 500px;
}
#container:after {
content : "";
clear: both;
display: block;
}
.article:first-child {
margin-left : -4px;
}
.article:last-child {
margin-right : -4px;
}
.article {
float: left;
width : 33.333%;
margin-right : 4px;
border : 1px solid blue;
}
<div id="container">
<div class="article">
A content
</div>
<div class="article">
B content
</div>
<div class="article">
C cotntent
</div>
</div>
<br />
<hr />
<button id="rotateBtn">Stop rotate</button>
Hope it helps :)
There are so many ways to do this. Here is a simple JSFiddle using jQuery that leaves you lots of room for improving. While you can certainly use a variable to hold the DIV's content I just used a hidden DIV as a temporary content holder. You could also optimize the rotateNews() function by holding the four DIV pointers in variables e.g. var $news1 = $("#new1"); placed first in the function.
Pure javascript solution: store the contents of you divs inside variables, then reassign the content of each div to other divs according to your needs.
setInterval(function(){
var contents_n1 = document.getElementById("news1").innerHTML;
var contents_n2 = document.getElementById("news2").innerHTML;
var contents_n3 = document.getElementById("news3").innerHTML;
document.getElementById("news1").innerHTML = contents_n3;
document.getElementById("news2").innerHTML = contents_n1;
document.getElementById("news3").innerHTML = contents_n2;
}, 30000);

Boolean test HTML textbox input compared to array values

I am trying to create a single textbox form on a webpage to boolean test the input submitted by the user. The input will be the website user's zip code. I want to make a predetermined array of zip codes that will test true.
If it is true (the zip code entered is included in the predetermined array), I want to display one bit of HTML, and if it tests false, I want to display another bit.
I've searched around and looked in some of my JavaScript books (I've just started learning) and haven't found an answer; could someone help me out with this? Thanks!
HTML:
<label id="input-label" class="invalid">
ZIP code: <input id="zipcode" />
<div class="valid-message">
Valid
</div>
<div class="invalid-message">
Invalid
</div>
</label>
CSS:
#input-label.valid .valid-message { display: block; }
#input-label.valid .invalid-message { display: none; }
#input-label.invalid .valid-message { display: none; }
#input-label.invalid .invalid-message { display: block; }
Javascript
function isValidZip(z) {
return ['12345','67890'].indexOf(z) != -1;
}
var label = document.getElementById('input-label');
var input = document.getElementById('zipcode');
input.onkeydown = function() {
label.className = isValidZip(input.value) ? "valid" : "invalid";
}
You could try something like this(might be a little off I'll double check then get back to you :) ):
var zipArr = ['98671','97006'];//insert the zip/post codes here
var userInputEl = document.getElementById('userInput');//Get the element could use tag names or it would be better actually if you used jQuery but yeah
var elToShow = document.getElementById('elementToShowIfNotFound');
var otherElToShow = document.getElementById('idOfOtherelementToShow');
var userInput = userInputEl.value();//might be .text()
if(zipArr.indexOf(userInput) === -1){//-1 means it isn't found in the array
zipArr.push(userInput);//pushes the new one onto the array
elToShow.style.display = 'block';//this changes the css display to block instead of it being hidden.
}else{
otherElToShow.style.display= 'block';
}
Might not be the best way to do this, but I'd suggest using jQuery it makes this process a lot easier.

Categories

Resources