There are already some answers on this site but couldn't figure out what I need.
Using the answer accepted as good given here: How can I change text after time using jQuery?
But, instead of having an alert, I'd like to make it reload to its first message (adding full codes for clarity:
function nextMsg() {
if (messages.length == 0) {
// once there is no more message, I don't know how to start the script over (loop it)
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var messages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse();
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
On another answer I had also find something similar, but I couldn't add fade in and fade out:
var example = [' link1', ' link2'];
textSequence(0);
function textSequence(i) {
if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = example[i];
textSequence(++i);
}, 5000); // milliseconds
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<div id="sequence"></div>
This may seem like a simple answer, but while I understand html and css to an extent, jscript is still out of my reach, so an answer with some clarity onto it would be great.
Thanks to anyone that will answer.
Using pop in the first example is actively removing elements from your messages array - so you can't "start the script over" because you have basically destroyed your data.
Think of pop as taking an items out of a bag one at a time and throwing them away - obviously when there are no items left in the bag - you can't then start again trying to get items out of the bag - because there is nothing left in the bag.
function nextMsg(index) {
if (messages.length === index) {
nextMsg(0);
} else {
$('#message').html(messages[index])
.fadeIn(500)
.delay(1000)
.fadeOut(500, () => nextMsg(index + 1));
}
};
var messages = [
' link1',
' link2',
' link3',
' link4'
];
$('#message').hide();
nextMsg(0);
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
As you can see there is no need to copy or duplicate the data - nor is there any need to reverse the messages.
Simply use the message index to keep track of which message to display and loop the index.
You are using pop to empty the original list. You need to keep the original list in place in order to start over:
function nextMsg() {
if (messages.length == 0) {
messages = copy(originalMessages);
nextMsg();
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var originalMessages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse()
var messages = copy(originalMessages);
function copy(x){
return JSON.parse(JSON.stringify(x));
}
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
Try it :
var example = [' link1', ' link2'];
textSequence(0);
function textSequence(i) {
$('#sequence').html(example[i])
$('#sequence').fadeIn(500)
if (example.length > i) {
setTimeout(function() {
$('#sequence').fadeOut(500);
setTimeout(function() {
textSequence(++i);
},600);
}, 5000);
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id='sequence'></div>
Related
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
I am making a website using HTML, CSS, MySQL and Javascript that will allow the user to login and play a quiz, the quiz has 40 questions.
The Javascript code bellow is a countdown timer, that contains the variable named "questions" after 40 seconds, it will pass automatically to the next question.
var i = 0;
var cEl = document.getElementById('countdown');
var qEl = document.getElementById('question');
var questions = [
'Question1 ?',
'Question2 ?',
'Question3 ?',
'Question4 ?'
];
var Countdown = function (time) {
this.time = time;
this.observers = [];
};
Countdown.prototype.start = function () {
setTimeout(function () {
if (this.time-- > 0) {
this.updateObservers();
this.start();
}
}.bind(this), 1000);
};
Countdown.prototype.addObserver = function (observer) {
this.observers.push(observer);
};
Countdown.prototype.updateObservers = function () {
var i, l = this.observers.length;
for (i = 0; i < l; i++) {
this.observers[i](this.time);
}
};
function printTime (time) {
cEl.innerHTML = time + 's';
}
function nextQuestion (time) {
if (time <= 0) run();
}
function run () {
var c;
if (i < questions.length) {
qEl.innerHTML = questions[i++];
c = new Countdown(40);
c.addObserver(printTime);
c.addObserver(nextQuestion);
printTime(c.time);
c.start();
} else {
document.body.innerHTML = 'Fin du quiz';
}
}
run();
And this is the part of my "quiz.php" file where I want the questions to be inserted :
<!doctype html>
<html>
<head>
<title>
Quiz
</title>
</head>
<body class="no-scroll">
<div>
<!-- some code here -->
</div>
<!-- some code here -->
<script src="js/countdown_script.js"></script>
</body>
</html>
For now, the questions are in the following variable :
var questions = [
'Question1 ?',
'Question2 ?',
'Question3 ?',
'Question4 ?'
];
But I want to use questions and their answers that are already in a database, each question has 2 or 3 possible answers, I've read that I'm not supposed to add the php code inside of a .js file, I tried to add the questions variable in the php code bellow but it did not work :
<!doctype html>
<html>
<head>
<title>
Quiz
</title>
</head>
<body class="no-scroll">
<div>
<!-- some code here -->
</div>
<!-- some code here -->
<script src="js/countdown_script.js">
var questions = [
'Question1 ?',
'Question2 ?',
'Question3 ?',
'Question4 ?'
];</script>
</body>
</html>
What is the best way to do that in my case? Given that I'm still a beginner and I only know html, css, some javascript, php and mysql.
You need to make a small API.
Step 1. make an additional page in your application that will output clean JSON array with data from the dataabse
For example: myApiWithQuestions.php
{
questions: {
question1: {
"content":"content of the question",
"possibleAnswers":[
"something", "another answer"
]
},
question2: {
"content":"content of the question",
"possibleAnswers":[
"something", "another answer"
]
},
}}
Step 2: Make an ajax call using JQuery to look for the page you have just created
$(document).ready(){
$.ajax({
url: "myApiWithQuestions.php",
})
.done(function( data ) {
//use data as an array, iterate through it and put your questions to the DOM
});
}
On .done function continue with execution of your script
Where did you read that you're not supposed to run PHP code in Javascript?
Anyway, it doesn't really matter: you can. I do it all the time.
<script type="text/javascript" src="js/countdown_script.js">
<script type="text/javascript"><!--
var questions = [
<?php
//create and run your mysql query
//loop through your results
while($row=mysql_fetch_array($results)){
//print your results in javascript format
printf("'%s ?'\n",$row['question']);
}
?>
];
--></script>
I'm trying to create a palindrome checker. And now it seems that my lengthChecker() is no longer being called, nor is the condition whenever a word isn't a palindrome, then say it's not a palindrome. What could be the issue?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lesson #6 Homework</title>
<script type="text/javascript" src="./js/palindrome.js"></script>
</head>
<body>
<h1>Is it a Palindrome?</h1>
<div id="mainCont">
<p>Hello. Please enter a word, and I'll see if it is a palindrome.</p>
<p>Word:
<input type="text" id="str" name="string" />
<button id="checkInput">Submit</button>
</p>
</div>
</body>
</html>
Here is the JS as of now:
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10 ) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert ("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome();
}
function palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
}
if (str == revStr) {
isPalindrome();
} else {
alert(str + " -is not a Palindrome");
}
}
function isPalindrome() {
alert(str + " is a Palindrome.");
}
document.addEventListener("DOMContentLoaded" , function(e){
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
You have your Javascript linked in the head element, so it is executed before the <button id="checkInput"> gets into the DOM. Move it to the end of body or make it deferred.
Because you are tying to access your button, before your page is properly loaded.
You need to get your button and bind your event handler, when DOM is loaded.
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
Hello im a little bit new on doing javascript and jquery please kinda help me on my problem. i would really appreciate it. Thank you!
On page 7-8 how can I remove the "disabled" on the "new game" button
Using jquery?
Here's the index.html:
<!DOCTYPE>
<html>
<head>
<link href="assets/css/blackjack.css" type="text/css" media="screen" rel="stylesheet">
<script src="assets/js/Modernizr.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/Mustache.js"></script>
<script src="assets/js/blackjack.js"></script>
</head>
<body>
<div class="wrapper">
<img src="assets/images/rocket-u-logo-large.png">
<h1>Blackjack</h1>
<p>Hi, thanks for stopping by our blackjack table. Pull up a chair and let's play...</p>
<div id="card-table">
<h2>Dealer</h2>
<div id="dealer-hand"></div>
<div id="status"></div>
<div id="player-hand"></div>
<h2>Player</h2>
<div id="player-options">
<button class="bj" id="new-game" disabled>New Game</button>
<button class="bj" id="hit">Hit</button>
<button class="bj" id="stand">Stand</button>
</div>
</div>
</div>
</body>
</html>
and Here's the js:
$('#bj').click(function () {
$('#hit').show();
$('#stand').show();
});
function initGame() {
var initErrors = [];
var errorMessage;
// Test if browser supports local storage
if (Modernizr.localstorage) {
// console.log("Local storage is supported.");
} else {
var errorStatus = "Local storage is not available"
// console.log(errorStatus);
initErrors.push(errorStatus);
}
// Test if browser supports mustache.js
var mustacheScript = $('script[src*="js/Mustache.js"]').length;
if (mustacheScript != 0) {
// console.log("Mustache loaded!");
} else {
var errorStatus2 = "Mustache not loaded."
// console.log(errorStatus2);
initErrors.push(errorStatus2);
}
function displayErrorMessage() {
// Test if initErrors array has any errors
if (initErrors.length != 0) {
if (errorStatus2 === undefined) {
errorStatus2 = "";
} else if (errorStatus === undefined) {
errorStatus = "";
}
var errorMessage = "Houston, we have a problem (" + errorStatus + ', ' + errorStatus2 + ").";
// console.log(errorMessage);
$('#status').append("<p>" + errorMessage + "</p>");
} else {
var successMessage = "Ready to play? Click 'New Game' to start...";
$('#status').append("<p>" + successMessage + "</p>");
// console.log(successMessage);
}
}
displayErrorMessage();
//Test 'boolean' return values
if (initErrors.length != 0) {
return false;
$('#new_game').attr("disabled", "disabled");
} else {
return true;
$('#new_game').removeAttr("disabled");
}
}
console.log(initGame());
$(document).ready(function () {
initGame();
});
You wrote the code yourself. but it was below return statement which will make it in accesible.
bring the return statement below
$('#new_game').removeAttr("disabled");
It should work.
You can try this:
$('#new_game').prop('disabled',false);
You can use anyone of listed below
$('#new_game').attr("disabled", false);
OR
$("#new_game").removeAttr("disabled");
OR
$("#new_game").prop("disabled",false);
$('#new-game').removeAttr('disabled');
Looks like your JS code has an error: in HTML <button class="bj" id="new-game", but in JS $('#new_game').removeAttr("disabled");. You use underscore instead of '-' in id.
I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>