How to create a pre-choice selection? - javascript

I was interested in creating a temporary screen before a page where someone could choose an option that would determine what they're shown.
Example: Contact page where the screen asks "Are you interested in contacting us regarding a purchase or to talk to our customer team". Once they click an option it would display the corresponding contact form (one emails customer team, the other emails the purchase team).
I'm not sure how to code this as I'm new to HTML/CSS/JavaScript but based on what I've learned so far I'm assuming this is more advanced JavaScript.

I can provide a simple example to give you some sense about it, but I would suggest you to get more basic front end training first.
if (window.confirm('Do you want load form a?')) {
document.getElementById('a').style.display = 'block';
} else {
document.getElementById('b').style.display = 'block';
}
https://jsfiddle.net/8LmL4vdr/1/

I'm not entirely sure what you asking, but it sounds like if you changed the elements' z-index values on the click of the buttons, it would work.
You can read more about z-index here.
Or, you can use display.
Here is an example:
function layerPages(page) {
if (page == "one") {
document.getElementById("pageOne").style.display = "block"; // shows first page if that is what is called
} else if (page == "two") {
document.getElementById("pageTwo").style.display = "block"; // shows second page if that is what is called
} else {
window.alert("error, wrong useage");
}
document.getElementById("originalPage").style.display = "none"; // hides main page
}
document.getElementById("buttonOne").addEventListener("click", function
myfunction() {layerPages("one");}); // adds event listener that states that when the first button is clicked, the first page is shown and the original is hidden using the function "layerPages" (declared above)
document.getElementById("buttonTwo").addEventListener("click", function
myfunction() {layerPages("two");}); // adds event listener that states that when the second button is clicked, the second page is shown and the original is hidden using the function "layerPages" (declared above)
#originalPage {
background-color: black;
width: 100px;
height: 100px;
}
#pageOne, #pageTwo {
display: none; /*You need to make sure that both #pageOne and #pageTwo start out as display: none;*/
background-color: yellow;
width: 100px;
height: 100px;
}
#pageTwo {
background-color: orange;
}
<div id="originalPage">
<button id="buttonOne">Page One</button>
<button id="buttonTwo">Page Two</button>
</div>
<div id="pageOne"></div>
<div id="pageTwo"></div>
<!--The content goes into each div, I'm sure that you can figure that out-->

Related

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.

Show popup when <a href >link clicks

I just want to make a URL with a button when It clicks it must show a dialog with my message. Is there any way to achieve in HTML?. Already searched google, as a beginner I don't understand much. So a simple tutorial might help me.
the link should be like www.google.com/webpage/#popup
dialog must be shown in the center of the screen.
onClick with a function:
<script type="text/javascript">
function AlertIt() {
alert("ATTENTION! THIS IS AN ALERT");
}
</script>
click me
Complex single one-liner:
<a href="http://example.com/"
onclick="return alert('Please click on OK to continue.');">click me</a>
You can make use of a hashchange-event!
Make a check-hash function and call it initially, so that loading the URL with the hash has the same behavior as changing the hash when already on-page.
You could create an array holding the IDs of the elements that should "listen" for such a hashchange, and give them a specific class (e.g. .hash-selected) when their ID equals the hash.
const hashes = ["#popup"]; // List of IDs that are "listening"
let lastHash = "";
function checkHash() {
if (hashes.includes(lastHash)) // Remove class from last selected element
document.querySelector(lastHash).classList.remove("hash-selected");
if (hashes.includes(location.hash)) // Add class to current selected element
document.querySelector(location.hash).classList.add("hash-selected");
// Save current hash as 'lastHash' for first if-statement when calling 'checkHash()' again
lastHash = location.hash;
}
checkHash(); // Initial function-call for same behavior on "page-open"
window.addEventListener("hashchange", () => checkHash());
body {margin: 0}
#popup {
position: absolute;
border-bottom: 1px solid black;
width: 100%;
transform: translateY(-100%);
background: lightgreen;
}
#popup.hash-selected {transform: translateY(0)}
<div id="popup">
<p>Some sample text</p>
Close
</div>
Open popup
We could even easily fill the hashes-array with IDs of elements that have a specific class, like .hash-listen:
const hashes = [];
for (let el of document.querySelectorAll(".hash-listen"))
hashes.push("#" + el.id);
// ...
Sidenote
To remove hashchanges from the browser-history, you should take a look at this answer that demonstrates the history.replaceState()-function.
Click Here
<script>
function myAlert() {
alert('hello there!');
}
</script>

How can we stop the execution of javascript for a while until a decision is made?

I want to build my own popup box using div's (not the browser default). So when I display my own popup I want to stop the javascript execution until the user clicks a button on my own popup, same as the default confirmation popup in browsers. Is there a way to do this? If so how? I would like to avoid using jQuery.
You can't (and shouldn't) block JavaScript execution. It would be possible by introducing an endless while loop, but that would seriously degrade performance and also affect the handling of click events.
So, the best and probably only way to do this, is to use a callback that is called when you press a button. This does mean that you can't call this alternative confirm method in a synchronous way, though. Instead you can provide a callback that is executed when one of the buttons is pressed.
I hacked together an example. This is just made up on the fly, and only has some rudimentary styling. If it contains minor flaws, please forgive me.
/**
* The alternative confirmation function
*/
window.myConfirm = function(options) {
// Create the elements
var popup = document.createElement('div');
var box = document.createElement('div');
var ok = document.createElement('button');
var cancel = document.createElement('button');
// Style them
popup.className = 'lightbox';
box.className = 'dialog';
ok.className = 'button buttonOK';
cancel.className = 'button buttonCancel';
// Button texts
ok.innerText = 'OK';
cancel.innerText = 'Cancel';
// Click handlers.
ok.onclick = function(event) {
popup.parentNode.removeChild(popup);
options.onConfirm();
}
cancel.onclick = function(event) {
popup.parentNode.removeChild(popup);
options.onDecline();
};
// Clicking the box does nothing.
box.onclick = function(event){
event.stopPropagation();
};
// Clicking the popup equals cancel.
popup.onclick = cancel.onclick;
// Add all elements to the document.
popup.appendChild(box);
box.innerHTML = "<div><h2>" + options.title + "</h2>" + options.prompt + "</div>";
box.appendChild(ok);
box.appendChild(cancel);
// Finally show the box.
document.body.appendChild(popup);
};
/**
* The call
*/
myConfirm({
title: "Confirm",
prompt: "Are you sure?",
onConfirm: function() {
// The code that is executed when user presses OK.
alert('You confirmed');
},
onDecline: function() {
// Code executed on cancel, or when clicking next to the box.
alert('You declined');
}
});
.lightbox {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
text-align: center;
}
.dialog {
display: inline-block;
margin-top: 50px;
background-color: white;
padding: 50px;
}
.dialog div {
text-align: left;
}
There is no way of stopping the execution, get an input from the user and then continue from some point without using JavaScript popup boxes. You can build one on your own with html components and display it with buttons, provide call backs. You would need to block the window from user access, take the input and then unblock the window. You may use Javascript frameworks like jQuery to get a better styled, enhanced and optimized component. Here is piece of code demonstration:
JavaScript
function myCancelClick() {
hidePrompt();
alert("Cancel");
}
function myOkClick(){
hidePrompt();
alert("Ok");
}
function showPrompt() {
document.getElementById("promptPane").style.display = '';
document.getElementById("displayPane").style.display = 'none';
}
function hidePrompt() {
document.getElementById("promptPane").style.display = 'none';
document.getElementById("displayPane").style.display = '';
}
HTML body
<body>
<div id="displayPane">
<input type="button" onclick="showPrompt()" value="Show Prompt"/>
</div>
<div id="promptPane" style="display: none;">
<div id="myPrompt">what would you like to click?<input type="button" onclick='myCancelClick();' value="Cancel"/><input type="button" onclick='myOkClick();' value="Ok"/>
</div>
</div>
</body>
Fiddle
If you know, how much time you want to stop for; try using setTimeout() function of Javascript to produce a delay

mouseover event propagation issue - Manually propagate

I am implementing an User Interface for a project I'm working on and can be found here : Toobrok
Each time the mouse of the user enters a div, a class is added to this div to highlight it, I use the stopPropagation() method to restrict the highlighting to the div whose z-index is higher (the top div in the z axis).
However, sometimes, my user needs to select an element hidden by another one, when the dimensions of the 2 elements are different, and if the bottom div is larger, he can find some points of the bottom div not hidden by the top one, but when the dimensions are the same, I would like the user to be able to press a key to change the depth (on the z-axis) of his selection.
The relevant code is given below (in CoffeeScript), but a javascript solution would also help me:
Ui.bind = (elements, index) ->
ids = Ui.getIdSelector(elements)
$(ids).attr("centroid", index)
$(ids).mouseover (event) ->
event.stopPropagation()
Ui.highlight $(ids)
$(ids).mouseout (event) ->
event.stopPropagation()
Ui.resetHighlight $(ids)
I hope the question is clear and looking forward to your answer.
This is an example of HTML to consider :
<!DOCTYPE html>
<html>
<head>
<title> Sample page </title>
</head>
<body>
<div id="container">
<div id="child1">Some text...</div>
</div>
</body
</html>
And the related css :
#container {
height: 200px;
width: 500px;
}
#child1 {
height: 90%;
width: 90%;
}
When the mouse enters the child1 element, this element is highlighted, I want the container element to highlight when the user press a specific key.
I could use the JQuery parent() function to select that element on this example, but I am not sure it is a good solution, sometimes, the parent can have a size of 0px and and then a mouseover on this element would not be consistent. I want to select the element normally selected by Javascript if I do not use the stopPropagation() event.
I actually just found something that might help :
How to undo event.stopPropagation in jQuery?
But I cannot use that in my case... Because my condition is another user action, and I cannot synchronously wait for an user to do something.
I started writing code but then decided to leave implementation to you. Here is the text explanation:
At some point of time (probably when user press button to cycle through all hovered elements) you have to find all candidates for highlighting. There is no other way to do it rather than manually loop through all your elements and check if mouse position is inside their bound rect. You can get mouse coordinates from argument in mouseover callback. Save all these hovered elements in some array.
Next, you have to manually choose which element to highlight. Just highlight the first element in saved array and move the element to the end of array. You also may want to increase this element z-index and add callback for mouseout to this element.
Hope it helps, feel free to ask if you need more details.
You could use the CSS property pointer-events to make the child insensitive. Then events will be targeted to the element displayed below. For simple highlighting you should use pure CSS, however, jQuery can be helpful not to highlight the parent element as well while child is hovered without Ctrl.
Some example (also uploaded to JSFiddle, click into the output pane to make it responsive for keyboard events):
<div id="container1" class="container">
<div id="child1" class="child">Some text...</div>
</div>
div { border:1px dashed red; } /* for demo */
.container
{ height: 200px;
width: 500px;
}
.child
{ height: 90%;
width: 90%;
}
.insensitive
{ pointer-events:none;
}
.container:hover:not(.no-hilight),
.child:hover
{ background-color:yellow;
}
/* other color for demo */
.child:hover{ background-color:green; }
// make events passthrough child when <Ctrl> is held down
$(document).on('keydown keyup', function(ev) {
if (ev.key === 'Control') // for performance
$('.child')[ev.ctrlKey?'addClass':'removeClass']('insensitive');
});
// don't hilight container when child is hovered
$('.child').on('mouseover', function(ev)
{
$('.container').addClass('no-hilight');
});
// never suppress hilight when container is hovered directly
$('.container').on('mouseover', function(ev)
{ if(ev.target === ev.currentTarget)
$('.container').removeClass('no-hilight');
});
// just test which element a click is targeted to
$(document).on('click', function(ev)
{ console.log('click:', ev.target);
});
var preId = 0;
function makeBlack(id)
{
if(id)
{
$('#'+id).css('border-color','black');
}
}
function makered(id)
{
$('#'+id).css('border-color','red');
}
$(document).ready(function(){
$('div').mouseout(function() {
var currentid = this.id;
makeBlack(currentid);
preId = currentid;
});
$('div').mouseleave(function() {
var currentid = this.id;
makeBlack(currentid);
preId = currentid;
});
$('div').mouseover(function() {
var currentid = this.id;
makeBlack(currentid);
makered(preId);
preId = currentid;
});
$('div').mouseenter(function() {
var currentid = this.id;
makered(currentid);
preId = currentid;
});
});
Have you tried something like this for the CSS?
#container.hover{
height: 200px;
width: 500px;
//add a background-color to that element since its a div element
//background-color: (colour)
}
i should hope that the div element would automatically highlight the container div with whichever color you have selected

4 toggle buttons speak javascript to each other but none of them are good listeners

update at the bottom
There are 4 divs that are set to look like toggle buttons. When a button is toggled on:
-it is animated as a pressed button,
-it retrieves some content and it places that content into a box, and then
-it returns a value of 1 to an array.
(no problem.)
Problem:
When there is already one button button pressed, I don't understand how to toggle the first button off without also turning the other one off or affecting the other buttons. How can I pass the output of one button to the others so they know who they have to turn off when they turn on?
My solution thus far has been to create 2 arrays:
var arrayValues [ a, b, c, d]; //the values of each button state: [0,0,0,0] <-all off | all on-> [1,1,1,1]
var addedValues = [a + b + c + d]; //the values of each array item added together: [0+0+0+0]= 0 <-all off | all on-> [1,1,1,1]=4
and then
if (addedValues = 0) {
console.log("cool, nothing is pressed yet. I am going to return true, but where does that return value go? How can I access it?");
return true;
} else if (addedValues > 1) {
console.log("ok I now know that at least one button has already been pressed, but how can I tell the other buttons which one was already pressed?");
}
For example if the first button is toggled on
arrayValues = [1,0,0,0]
and now the second button has been toggled on so it says
arrayValues = [1,1,0,0]
but how can I pass that information into all of the buttons? This next part is obviously flawed but it's the only thing I could think of doing:
} else if(addedValues >= 2) {
arrayValues[0] = arrayValues[0] - 1;
arrayValues[1] = arrayValues[1] - 1;
arrayValues[2] = arrayValues[2] - 1;
arrayValues[3] = arrayValues[3] - 1;
}
so now, the only values that are not negative are the two buttons in active states... but that does nothing for because we already knew that. How can I tell the buttons which button to subtract 1 from without affecting any of the other buttons?
Update: To see the madness in context http://jsfiddle.net/Luhring/EjW7A/23/
*update: *
Just to clarify: the buttons aren't only just toggling their appearances, they're changing other content displayed on the page:
When you click each button the content changes. each button has 1 original group of original content that is toggled on/off with the button. like changing the channel on a tv screen with a remote control.
so if button 1 is pressed, when button 2 is pressed button 1 must turn off (removing its' content and animating back up to its' original position) in order to allow button 2's stuff to display.
shout out to #nbrooks for writing 4 lines of code that more or less did as much as I did in +100. Still not solved but his is WAY more efficient than mine (you can see his version here: http://jsfiddle.net/EjW7A/20/ ) )
Updated Demo, according to new reqs: http://jsfiddle.net/EjW7A/24/
$(function() {
$('.plain').click(function() {
var newClassName = $(this).is('.selected') ? '' : this.id;
if ($(this).is('#content')) return;
$(this).toggleClass('selected', 1000);
$('#content').attr('class', 'plain '+newClassName);
$('.selected').not(this).removeClass('selected');
});
});​
Update to your fiddle demo
The best way to do this is just give the elements a common class, to which you can bind a click handler and a css rule. This will accomplish your function of only having one button being pressed at a time, plus the ability to turn it on/off without affecting the others.
Javascript (jQuery):
$(function() {
$('.plain').click(function() {
$(this).toggleClass('selected');
$('.selected').not(this).removeClass('selected');
});
});​
HTML
<div id="a" class="plain">
<p>A</p>
</div>
CSS
.plain {
width: 200px; height: 200px; margin: 20px; text-align:center; float: left;
font-size: 100px; color:#fff; background-color:red;
}
p { margin-top: 25%; margin-bottom:25%; }
.selected { background-color: blue; }
If you are doing the submitting with JavaScript, then this should be a much simpler approach: http://jsfiddle.net/EjW7A/15/
HTML
<div id="a" class="a1 toggleButton">
<p>A</p>
</div>
<div id="b" class="b1 toggleButton">
<p>B</p>
</div>
<button id ="test">test</button>​
JavaScript
jQuery(function() {
jQuery(".toggleButton").click(function() {
jQuery(".toggleButtonToggled").removeClass("toggleButtonToggled");
jQuery(this).addClass("toggleButtonToggled");
});
jQuery("#test").click(function() {
var value = jQuery(".toggleButtonToggled:first").attr('id');
alert("Toggled button is: "+ value);
});
});​

Categories

Resources