I need to run a script only when a hidden div (display:none) is active.
When press "radio button" display "div1" with the fake loader and after 3 seconds display another div called "my_div".
But if the user don't press the "radio button", the random text on "my_div" still appears.
I need to fix this, only show this random text "my_div" if the user press the radio button. So, when user press "radio button" display "div1" with fake loader and after 3 seconds, display another div (already working), if not press the button, nothing happens (don't run the random script).
Working:
https://jsfiddle.net/zto6gv1c/3/
This is my project:
function show1() {
document.getElementById('div1').style.display = 'none';
}
function show2() {
document.getElementById('div1').style.display = 'block';
}
var r_text = new Array();
r_text[0] = "Disponível";
r_text[1] = "Indisponível";
r_text[2] = "Disponível";
r_text[3] = "Indisponível";
r_text[4] = "Disponível";
r_text[5] = "Disponível";
r_text[6] = "Indisponível";
r_text[7] = "Disponível";
r_text[8] = "Indisponível";
r_text[9] = "Disponível";
r_text[10] = "Indisponível";
r_text[11] = "Disponível";
var i = Math.floor(7 * Math.random())
document.write(r_text[i]);
window.onload = function() //executes when the page finishes loading
{
setTimeout(func1, 3000); //sets a timer which calls function func1 after 2,000 milliseconds = 2 secs.
};
function func1() {
document.getElementById("my_div").className = "show";
}
.hide {
display: none;
}
p {
font-weight: bold;
}
.show {
display: block;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Deseja chegar a disponibilidade do produto?</p>
<input type="radio" name="tab" value="igottwo" onclick="show2();" /> Sim
<div id="div1" class="hide">CHECANDO</div>
<div id="my_div" class="hide"></div>
I hope this is what you are looking for. Let me know if I am nearby.
function show2() {
document.getElementById('div1').style.display = 'block';
setTimeout(func1, 3000);
}
Then, replace document.write with below
document.getElementById("my_div").innerHTML = r_text[i];
Then replace your window.onload code with below
window.onload = function() //executes when the page finishes loading
{
setTimeout(function(){
if(document.getElementById('div1').style.display != 'block'){
func1();
}
}, 3000); //sets a timer which calls function func1 after 2,000 milliseconds = 2 secs.
};
Oke so WHEN class hide has display none - you want to run some other code ?
You can check the visibility this way:
var isVisible = document.getElementsByClassName("hide")[0].style.display == "block";
if(isVisisble){
this thing is hiden
}else{
this thing is not hiden
}
We use getElementsByClassName because you put it on a class with the name 'hide' - there is only one of these elements present so we use [0] to get the first one (the only one) then we use the style.display to check the value.
Related
<html>
<body>
<div>
<img src="cat.jpg" id="cat" onclick="alertfunction()">
<img src="dog.jpg" id="dog" onclick="alertfunction()">
<img src="frog.jpg" id="frog" onclick="movefunction()">
<img>
</div>
</body>
<script>
function alertfunction() {
alert("Don't click me, click the frog");
}
function movefunction(){
}
</script>
</html>
Here, what i need help with, Whenever the user clicks the last picture, move to first.
Please help me.
You can change the source of the image whenever the user clicks on an image for instance:
let cat = document.getElementById("cat");
let frog = document.getElementById("frog");
function moveFunction() {
if(frog.src == "frog.jpg"){
frog.src = "cat.jpg";
}
else {
frog.src = "frog.jpg";
}
}
What you need to search for is DOM manipulation in Javascript. Here is a simple way to do what you ask for. I tried to make it as explanatory as possible.
<html>
<body>
<div id="animals">
<img src="cat.jpg" id="cat">
<img src="dog.jpg" id="dog">
<img src="frog.jpg" id="frog">
</div>
</body>
<script>
// animals variable here is a NodeList which is kind of like Array,
// but it is not enumerable (you cannot loop over it).
var animals = document.querySelectorAll('#animals > *');
// Here we convert it to an actual Array.
var animalsArray = Array.from(animals);
// We are going to add click listeners on every single of them.
animalsArray.forEach(function (animal) {
// Add an event listener to this img element.
animal.addEventListener(
// The listener should observe click events.
'click',
// The listener will call this function
// when a click event is triggered.
function (event) {
// This is the order number of the clicked animal image.
// Assuming that you have 3 images on the page, this number
// will be 0, 1 or 2.
// 0 marking the image as the first of rest, and 2 marking it
// as the last of them.
var positionOfThisAnimal = animalsArray.indexOf(this);
// animalsArray.length will give you the number of images in
// the `animalsArray` Array.
// If the position of the clicked animal image is smaller than
// the highest it can be (which is `2` for 3 images), it is not
// the last one, and we will alert the user with a message.
if (positionOfThisAnimal < animalsArray.length - 1) {
alert("Don't click me! Click the frog.");
// Because all we have to do for these not-the-last-one
// images is to alert the user, we are returning a void
// (empty) result here which effectively stops the function
// from executing the rest of the lines we have below.
return;
}
// Here we are taking the clicked animal image (which is the
// last one in the list) and we are moving it to the first
// place in the div with ID "animals".
document.querySelector('#animals').prepend(this);
},
// This `false` means the listener should not be marked as passive.
//
// Passive listeners are asynchronous, meaning that the browser
// will *not* wait for your function to complete executing before
// continuing to wait for other user inputs like mouse moves or
// keyboard strokes.
//
// The browser will wait for active listeners. This has a downside
// though. If your function takes too long to complete, the user
// will notice that their browser (or just the current tab) freezes
// and won't let user interact with the page until the execution
// is completed.
false,
);
});
</script>
</html>
const img1 = document.querySelector('#cat');
const img2 = document.querySelector('#dog');
const img3 = document.querySelector('#frog');
const imgUrl = img3.src;
img1.addEventListener('click', () => {
if(img1.src === imgUrl) {
let temp = img1.src;
img1.src = img2.src;
img2.src = img3.src;
img3.src = temp;
let temp2 = img1.id;
img1.id = img2.id;
img2.id = img3.id;
img3.id = temp2;
}
else {
alert('Don\'t click me, click the frog');
};
});
img2.addEventListener('click', () => {
alert('Don\'t click me, click the frog');
});
img3.addEventListener('click', () => {
if(img3.src === imgUrl) {
let temp = img1.src;
img1.src = img3.src;
img3.src = img2.src;
img2.src = temp;
let temp2 = img1.id;
img1.id = img3.id;
img3.id = img2.id;
img2.id = temp2;
}
else {
alert('Don\'t click me, click the frog');
};
});
img {
width: 300px;
height: 300px;
}
<div>
<img src="cat.jpg" id="cat">
<img src="dog.jpg" id="dog">
<img src="frog.jpg" id="frog">
</div>
We can do this with flex and order in the CSS, check the code below, instead of images, i used divs with colors.
.maindiv {
display: flex;
}
#frog {
padding: 10px;
width: 20px;
background: red;
}
#cat {
padding: 10px;
width: 20px;
background: blue;
}
#dog {
padding: 20px;
width: 10px;
background: green;
}
<html>
<body>
<div class="maindiv">
<div id="cat" onclick="alertfunction()">cat</div>
<div id="dog" onclick="alertfunction()">dog</div>
<div id="frog" onclick="movefunction()">frog</div>
</div>
</body>
<script>
function alertfunction() {
alert("Don't click me, click the frog");
}
function movefunction(){
if (document.getElementById('frog').style.order == '1') {
document.getElementById('frog').style.order = '3';
document.getElementById('cat').style.order = '1';
document.getElementById('dog').style.order = '2';
} else {
document.getElementById('frog').style.order = '1';
document.getElementById('cat').style.order = '2';
document.getElementById('dog').style.order = '3';
}
}
</script>
</html>
I want to create a toast notification in javascript. When the user has done fine, a message box (the toast) should appear with a green color and the text "successfull" or whatever.
If not, the color is red and the text should be "failure". This div should be sliding from the top of the center of the screen, stay for 3 sec and after that, it should be removed from the DOM.
I got this one here, to create my div
CreateToast(isValid) { // Toast notification
var toastDiv = document.createElement("div");
var toastMessage;
var foreColor;
var backgroundColor;
var borderColor;
if (!isValid) {
toastMessage = "Failure";
foreColor = "";
backgroundColor = "";
borderColor = "";
} else {
toastMessage = "Success";
foreColor = "";
backgroundColor = "";
borderColor = "";
}
toastDiv.innerHTML = toastMessage;
document.body.appendChild(toastDiv);
}
But what I don't know is, how to setup the rest of it. Where to place it, how it slides down from the top center etc.
I know, I can delete the div by using
toastDiv.remove(); // Delete the element from the DOM
but how to use it when it comes to "Destroy it after 3 sec" ?
Since you tagged jQuery to your question, I assume you want to use some jQuery methods.
So this is the basic example: (I'm sure you will be able to style it as you wish)
To each created div, you have to assign a unique id in order to be able to make it slideDown() and to .remove() it.
So I added a toastCounter to create this id.
var toastCounter=0;
function CreateToast(isValid) { // Toast notification
var toastDiv = document.createElement("div");
// Give it a unique id
toastDiv.id = "toast_"+toastCounter;
// Make it hidden (necessary to slideDown)
toastDiv.style.display = "none";
var toastMessage;
var foreColor;
var backgroundColor;
var borderColor;
if (!isValid) {
toastMessage = "Failure";
foreColor = "";
backgroundColor = "";
borderColor = "";
} else {
toastMessage = "Success";
foreColor = "";
backgroundColor = "";
borderColor = "";
}
toastDiv.innerHTML = toastMessage;
document.body.appendChild(toastDiv);
// Increment toastCounter
toastCounter++;
}
$("#test1").on("click",function(){
CreateToast(true);
var thisToast = toastCounter-1;
// Make it slide down
$(document).find("#toast_"+thisToast).slideDown(600);
setTimeout(function(){
$(document).find("#toast_"+thisToast).slideUp(600,function(){ // Slideup callback executes AFTER the slideup effect.
$(this).remove();
});
},3000); // 3sec.
});
$("#test2").on("click",function(){
CreateToast(false);
var thisToast = toastCounter-1;
// Make it slide down
$(document).find("#toast_"+thisToast).slideDown(600);
setTimeout(function(){
$(document).find("#toast_"+thisToast).slideUp(600,function(){ // Slideup callback executes AFTER the slideup effect.
$(this).remove();
});
},3000); // 3sec.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test1">TRUE</button>
<button id="test2">FALSE</button>
I think based on your requirements you should take a look at the toastr library. I use it myself for several projects and it has a great API which allows a lot of customization.
See: https://github.com/CodeSeven/toastr
You can show toast with JsFrame.js like below.
https://riversun.github.io/jsframe/examples/v150/toast_simple.html
<!DOCTYPE html>
<html>
<body>
<script src="https://riversun.github.io/jsframe/jsframe.js"></script>
<script>
const jsFrame = new JSFrame();
jsFrame.showToast({
html: 'This is a simple toast', align: 'top', duration: 2000
});
</script>
</body>
</html>
Here is the library.
https://github.com/riversun/JSFrame.js
I'm trying to create a game with dialogue, and I want my text to change as the player clicks on a next image to progress the story.
For example:
Page loads - "Hi, I'm Joe."
Clicks sliced Image once - "Nice to meet you."
Clicks 2nd time - "How are you?"
I have tried onClick but that only allows me to change it once, I've tried using var counter as well but to no avail, it overrides my previous commands, which part of this am I doing wrong here?
var clicks = 0;
function changeText() {
{
clicks = 1;
document.getElementById('text').innerHTML = "Ughh... my head... What
happened...?";
}
}
function changeText() {
{
clicks = 2;
document.getElementById('text').innerHTML = "Testing 1 2 3";
}
}
function play() {
var audio = document.getElementById("audio");
audio.play();
}
<img onClick="changeText(); audio.play()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>
First off all - your changeText() system is flawed - you're overwriting the same function multiple times at the same time, so the only one of those that will ever get called is the last one you declare. JavaScript doesn't wait until a function gets called to continue with the program.
The audio.play() also won't work - but I'm assuming that's a work in progress.
I changed your code so that instead of setting count to a specific value, it increments every time the function gets called, and it updates the text to the correct value in an array. Here's the updated changeText function:
var count = 0;
var text = [
"Where... am I...?", /* note that this will never get called, it's simply here for filling up the array*/
"This is the first text!",
"And this is the second!"
]
var changeText = function() {
count++;
document.getElementById('text').innerHTML = text[count];
}
In the future, you'll probably also want to check if(text[count] != 'undefined'), and if so write something like "Bye!" instead.
Issues in your code
Multiple function declaration of changeText()
Extra {} in changeText()
You are not updating value of clicks.
In your html, you have written audo.play() but no audio object is available. It should be play(). I have called play() function in changeText() function. This keeps HTML clean.
Following is updated code:
var clicks = 0;
function changeText() {
var text = ""
clicks++;
switch(clicks){
case 1: text = "Ughh... my head... What happened...?";
break;
case 2: text = "Testing 1 2 3";
break;
}
document.getElementById('text').innerHTML = text;
play();
}
function play() {
var audio = document.getElementById("audio");
audio.play();
}
<img onClick="changeText()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>
I have seen questions similar to this one but not quite on point. I just want to do something really simple: when button 1 is clicked, it should hide and button 2 should appear; and then when button 2 is clicked, button 2 should hide and button 1 should show.
I am trying to do this by modifying the z-index, however it is not working.
This is the code I am using to do it:
if (attacker == player 1) {
document.getElementById("p1-play").style.zIndex = -1;
document.getElementById("p2-play").style.zIndex = 1;
}
else {
document.getElementById(p2-play).style.zIndex = -1;
document.getElementById(p1-play).style.zIndex = 1;
}
where p1-play is button 1 and p2-play is button 2
It would be better to use display:
var p1Play = document.getElementById("p1-play");
var p2Play = document.getElementById("p2-play");
if (attacker == player1) {
p1Play.style.display = 'none';
p2Play.style.display = 'block';
}
else {
p1Play.style.display = 'block';
p2Play.style.display = 'none';
}
Yes, I've searched high and low on Stack Overflow and seen some great solutions to this problem that's been solved time and time again with things like SimpleModal, jQuery.confirm and the like.
Problem is, I am developing for this low level device that doesn't allow for a JS framework to be utilized AND I am having to shoehorn this modal confirm into existing JS.
There is an existing script that I am at liberty to edit (but not rewrite) that does a few things like validate, concatenate a few inputs into a single variable, and more.
The script was written to:
Take some session variables and assign new variable names to them and format accordingly
Present a confirm to the user to see whether they want to use those variables to pre-populate the form on the page
Get some functions ready to validate inputs.
other stuff, like offer an abandonment scenario, among other things
Now, all was good when the "confirm" was in place as the script would pause until an OK or Cancel was provided. I am now presenting a modal on the page that I want to mock this behavior and the only way I can think of doing it is to remove that reliance on the line that goes through the confirm thing and NOT run the script until the user interacts with the modal.
Does anyone have an idea how to take what's in place and "wrap" it in a "listening" if/else scenario for each of the YES or NO possibilities?
Sorry if this is jumbled... my brain is all blended up at the moment, too.
As far as I know there is - so far - no way to halt scripts like the Browser specific alert() or confirm() Dialog does.
Frameworks like dojo for example try to mock this behaviour by putting a transparent DIV over the whole window to prevent clicks or other input while the Dialog is showing.
This is quite tricky as I have experienced, since Keyboard-Input may be able to activate Input Fields or Buttons behind this curtain. Keyboard Shortcuts or Field-Tabbing for example.
One sollution is to disable active Elements manually, which works quite well with me in most cases.
One or more function is passed to this "mock" Dialog to execute when an option was chosen.
Escpecially with ajax background activity the responsibilty to stop conflicting function calls while the Dialog is open lies with the developer.
Here is an example I came up with:
<html>
<head>
<title>Modal Dialog example</title>
<script type="text/javascript">
<!--
var ModalDialog = function(text,choices){
this._text = text;
this._choices = choices;
this._panel = null;
this._modalDialog = null;
this._disableElements = function(tag){
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++){
elements[i].disabled = true;
}
};
this._enableElements = function(tag){
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++){
elements[i].disabled = false;
}
};
this._disableBackground = function(){
if(this._panel){
this._panel.style.display = 'block';
}
else{
// lower the curtain
this._panel = document.createElement('div');
this._panel.style.position = 'fixed';
this._panel.style.top = 0;
this._panel.style.left = 0;
this._panel.style.backgroundColor = 'gray';
this._panel.style.opacity = '0.2';
this._panel.style.zIndex = 99; // make sure the curtain is in front existing Elements
this._panel.style.width = '100%';
this._panel.style.height = '100%';
document.body.appendChild(this._panel);
// Disable active Elements behind the curtain
this._disableElements('INPUT');
this._disableElements('BUTTON');
this._disableElements('SELECT');
this._disableElements('TEXTAREA');
}
};
this.close = function(){
// Hide Curtain
this._panel.style.display = 'none';
// Hide Dialog for later reuse - could also be removed completely
this._modalDialog.style.display = 'none';
// reactivate disabled Elements
this._enableElements('INPUT');
this._enableElements('BUTTON');
this._enableElements('SELECT');
this._enableElements('TEXTAREA');
};
this.open = function(){
var _this = this;
this._disableBackground();
if(this._modalDialog){
this._modalDialog.style.display = 'block';
}
else{
// create the Dialog
this._modalDialog = document.createElement('div');
this._modalDialog.style.position = 'absolute';
this._modalDialog.style.backgroundColor = 'white';
this._modalDialog.style.border = '1px solid black';
this._modalDialog.style.padding = '10px';
this._modalDialog.style.top = '40%';
this._modalDialog.style.left = '30%';
this._modalDialog.style.zIndex = 100; // make sure the Dialog is in front of the curtain
var dialogText = document.createElement('div');
dialogText.appendChild(document.createTextNode(this._text));
// add Choice Buttons to the Dialog
var dialogChoices = document.createElement('div');
for(i = 0; i < this._choices.length; i++){
var choiceButton = document.createElement('button');
choiceButton.innerHTML = this._choices[i].label;
var choiceAction = _this._choices[i].action
var clickAction = function(){
_this.close();
if(choiceAction)choiceAction();
};
choiceButton.onclick = clickAction;
dialogChoices.appendChild(choiceButton);
}
this._modalDialog.appendChild(dialogText);
this._modalDialog.appendChild(dialogChoices);
document.body.appendChild(this._modalDialog);
}
};
};
var myConfirm = function(text,okAction){
var dialog = new ModalDialog(text,[
{
label:'ok',
action : function(){
console.log('ok')
okAction();
}
},
{
label:'cancel'
}
]);
dialog.open();
};
-->
</script>
</head>
<body>
<form name="identity" action="saveIdentity.do">
<label>Firstname</label><input name="name" type="text"><br>
<label>Lastname</label><input name="name" type="text"><br>
<input type="button"
value="submit"
onclick="if(myConfirm('Do you really want to Commit?',function(){ document.forms['identity'].submit();}));">
</form>
</body>
</html>
In this code there is still an error concerning the availability of the stored choice-function (undefined) at execution time. The function variable is no longer available in the closure. If anyone has a sollution for this you are welcome to add to it.
Hope that comes near to what you need to know.
Updated version: fixed choiceAction undefined, added IE compatibility. Internet Explorer is one main reason to use this, since confirm() is now blocked by default.
<!doctype html>
<html><head>
<title>Modal Dialog example</title>
<script type="text/javascript"><!-- //http://stackoverflow.com/questions/4739740/yet-another-confirm-replacement-quesiton
var ModalDialog = function(text,choices) {
this._text = text;
this._choices = choices;
this._panel = null;
this._modalDialog = null;
this._disableElements = function(tag) {
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++) {
elements[i].disabled = true;
}
};
this._enableElements = function(tag) {
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++) {
elements[i].disabled = false;
}
};
this._disableBackground = function() {
if(this._panel) {
this._panel.style.display = 'block';
}
else {
// lower the curtain
this._panel = document.createElement('div');
this._panel.style.position = 'fixed';
this._panel.style.top = 0;
this._panel.style.left = 0;
this._panel.style.backgroundColor = '#000';
this._panel.style.opacity = '0.3';
this._panel.style.filter = 'alpha(opacity=30)'; //ie7+
this._panel.style.zIndex = 99; // make sure the curtain is in front existing Elements
this._panel.style.width = '100%';
this._panel.style.height = '100%';
document.body.appendChild(this._panel);
// Disable active Elements behind the curtain
this._disableElements('INPUT');
this._disableElements('BUTTON');
this._disableElements('SELECT');
this._disableElements('TEXTAREA');
}
};
this.close = function() {
// Hide Curtain
this._panel.style.display = 'none';
// Hide Dialog for later reuse - could also be removed completely
this._modalDialog.style.display = 'none';
// reactivate disabled Elements
this._enableElements('INPUT');
this._enableElements('BUTTON');
this._enableElements('SELECT');
this._enableElements('TEXTAREA');
};
this.open = function() {
var _this = this;
this._disableBackground();
if(this._modalDialog) {
this._modalDialog.style.display = 'block';
}
else {
// create the Dialog
this._modalDialog = document.createElement('div');
this._modalDialog.style.position = 'absolute';
this._modalDialog.style.backgroundColor = 'white';
this._modalDialog.style.border = '1px solid black';
this._modalDialog.style.padding = '16px';
this._modalDialog.style.top = '35%';
this._modalDialog.style.left = '30%';
this._modalDialog.style.zIndex = 100; // make sure the Dialog is in front of the curtain
var dialogText = document.createElement('div');
dialogText.style.padding = '0 10px 10px 0';
dialogText.style.fontFamily = 'Arial,sans-serif';
dialogText.appendChild(document.createTextNode(this._text));
// add Choice Buttons to the Dialog
var dialogChoices = document.createElement('div');
for(i = 0; i < this._choices.length; i++) {
var choiceButton = document.createElement('button');
choiceButton.style.marginRight = '8px';
choiceButton.name = i;
choiceButton.innerHTML = this._choices[i].label;
var clickAction = function() {
_this.close();
if(_this._choices[this.name].action) _this._choices[this.name].action();
};
choiceButton.onclick = clickAction;
dialogChoices.appendChild(choiceButton);
}
this._modalDialog.appendChild(dialogText);
this._modalDialog.appendChild(dialogChoices);
document.body.appendChild(this._modalDialog);
}
};
};
var myConfirm = function(text,okAction){
var dialog = new ModalDialog(text,[
{
label : 'OK',
action : function() {
console.log('ok');
okAction();
}
},
{
label : 'Cancel'
}
]);
dialog.open();
};
-->
</script>
</head>
<body>
<form name="identity" action="saveIdentity.do">
<label>Firstname</label><input name="name" type="text"><br>
<label>Lastname</label><input name="name" type="text"><br>
<input type="button" value="submit"
onclick="if(myConfirm('Do you really want to Commit?',function(){ alert('submitted') }));">
<!-- document.forms['identity'].submit(); -->
</form>
</body>
</html>