How short can this script be and still achieve the same thing - display a message "loading.." followed by an extra period every 1 second for 7 seconds [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
<script>
var dot = ".";
var counter = 0;
var message = "Loading Page";
function writeLoadingMessage(){
if (counter > 6) return;
setTimeout('writeMessage();',1000);
}
function writeMessage(){
document.getElementById('loadingMessageSpan').innerHTML = message + dot;
message += dot
counter++
writeLoadingMessage();
}
</script>
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan"></span>
<SCRIPT>writeLoadingMessage();</SCRIPT>
</BODY>

(function(){var i=6,a=setInterval(function(){document.getElementById('loadingMessageSpan').innerHTML+=".";!i--&&clearInterval(a);},1E3)})()
You will need to have Loading already in your span tag. As a note it is pointless to worry about getting it this small though. Also, the page will will have to be already loaded.

If you want it shorter: http://jsfiddle.net/pimvdb/wBFSy/.
<script>
var counter = 0;
function writeMessage() {
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter < 7) {
setTimeout(writeMessage, 1000);
}
}
window.onload = writeMessage;
</script>
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
</body>
Minifying also helps :)
var a=0;function b(){document.getElementById("loadingMessageSpan").innerHTML+=".";++a<7&&setTimeout(b,1E3)}window.onload=b

1) User setInterval instead.
2) Just set the message once and append . to end
3) Put all the js at the bottom
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script type="text/javascript">
var counter = 0;
var id = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter>6) {
clearInterval(id);
}
}, 1000);
</script>
</body>

If you really want it short you can go this route:
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script>
var counter = 0;
var interval = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter > 6)
clearInterval(interval);
},1000)
</script>
</BODY>
http://jsfiddle.net/kc3fb/2/

Related

How to output PHP inside JS/jQuery that generates HTML? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I have to run a PHP action that is inside HTML which is inside a JS script. The current code does an error because the function that renders HTML breaks the syntax. I am getting Uncaught SyntaxError: Unexpected token '='
Here is my code example:
<script type="text/javascript">
(function($) {
$('.menu-main').on('click', function() {
var page = window.location.href;
var mobile = $('.menu-item-mobile');
var search = '<div class="wpml-language-switcher">'<?php do_action('wpml_add_language_selector'); ?>'</div>';
setTimeout(function() {
if(mobile.find('form').length == 1) return;
mobile.html(search);
}, 50); //delay time
});
})(jQuery);
</script>
Here is the output with failed structure in line 8 (Uncaught SyntaxError: Unexpected token '='):
<script type="text/javascript">
(function($) {
$('.av-burger-menu-main').on('click', function() {
var page = window.location.href;
var mobile = $('.menu-item-search-mobile');
var search = '<div class="wpml-floating-language-switcher">'
<div
class="wpml-ls-statics-shortcode_actions wpml-ls wpml-ls-legacy-dropdown js-wpml-ls-legacy-dropdown" id="lang_sel">
<ul>
<li tabindex="0" class="wpml-ls-slot-shortcode_actions wpml-ls-item wpml-ls-item-lv wpml-ls-current-language wpml-ls-first-item wpml-ls-item-legacy-dropdown">
<a href="#" class="js-wpml-ls-item-toggle wpml-ls-item-toggle lang_sel_sel icl-lv">
<img
class="wpml-ls-flag iclflag"
src="https://sampledomain.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/lv.png"
alt=""
width=18
height=12
/><span class="wpml-ls-native icl_lang_sel_native">LV</span></a>
<ul class="wpml-ls-sub-menu">
<li class="icl-en wpml-ls-slot-shortcode_actions wpml-ls-item wpml-ls-item-en">
<a href="https://sampledomain.com/en/" class="wpml-ls-link">
<img
class="wpml-ls-flag iclflag"
src="https://sampledomain.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/en.png"
alt=""
width=18
height=12
/><span class="wpml-ls-native icl_lang_sel_native" lang="en">EN</span></a>
</li>
<li class="icl-ru wpml-ls-slot-shortcode_actions wpml-ls-item wpml-ls-item-ru wpml-ls-last-item">
<a href="https://sampledomain.com/ru/" class="wpml-ls-link">
<img
class="wpml-ls-flag iclflag"
src="https://sampledomain.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/ru.png"
alt=""
width=18
height=12
/><span class="wpml-ls-native icl_lang_sel_native" lang="ru">RU</span></a>
</li>
</ul>
</li>
</ul>
</div>
'</div>';
setTimeout(function() {
if(mobile.find('form').length == 1) return;
mobile.html(search);
}, 50); //delay time
});
})(jQuery);
</script>
Is there anything possible to avoid the syntax error?
If I were you I'd put the PHP contents into a template tag and grab the contents with jQuery. For example...
<script type="text/template" id="template-wpml_add_language_selector">
<?php do_action('wpml_add_language_selector'); ?>
</script>
<script type="text/javascript">
(function($) {
$('.menu-main').on('click', function() {
var templateContents = $('#template-wpml_add_language_selector').html();
var page = window.location.href;
var mobile = $('.menu-item-mobile');
var search = '<div class="wpml-language-switcher">' + templateContents + '</div>';
setTimeout(function() {
if(mobile.find('form').length == 1) return;
mobile.html(search);
}, 50); //delay time
});
})(jQuery);
</script>

How to store a variable in an Array using AngularJS? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there any function that i can use?
Or i need to create one? Or can i use push? It is modified script from this page:
http://code-maven.com/automatic-counter-using-angularjs
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script>
angular.module('CounterApp', [])
.controller('CounterController', function($scope, $timeout) {
var timer;
$scope.stored = [];
$scope.counter= 0;
$scope.stopCounter = function() {
$timeout.cancel(timer);
timer = null;
};
$scope.startCounter = function() {
if (timer === null) {
updateCounter();
}
$scope.stored.push(counter);
};
$scope.pushedVariable = function() {
$scope.stored.push(counter);
};
var updateCounter = function() {
$scope.counter++;
timer = $timeout(updateCounter, 1000);
};
$timeout.cancel(timer);
timer = null;
});
</script>
<div ng-app="CounterApp">
<div ng-controller="CounterController">
<button ng-click="stopCounter()">Stop</button>
<button ng-click="startCounter()">Start</button>
<button ng-click="pushedVariable()">Push</button>
{{counter}}
<p>Stored Variable 1: {{stored[0]}}</p>
<p>Stored Variable 2: {{stored[1]}}</p>
</div>
</div>
You just need to use $scope.stored.push($scope.counter); in your function instead of your current $scope.stored.push(counter); which is an undefined variable.
function(obj) {
var str = [];
for(var val in obj)
str.push(encodeURIComponent(val) + "=" + encodeURIComponent(obj[val]));
}
Where "obj" is your object.

I made a jquery script and I need help on how to make it auto switch between the 4 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make this script auto change between the four after 30 seconds, I am not to good at jquery but I wanted to give it a try. This is all on a .php page I am using to bring up the javascript from my other folders.
<div id="subnavi">
<div id="subnavi-user">
<div style="margin-top:7px"><b>Fact:</b> <script language="JavaScript">
var r_text = new Array ();
r_text[0] = "{hotelName} was founded in 2011 by Kyle";
r_text[1] = "{hotelName} strives to remain as professional as possible.";
r_text[2] = "{hotelName} will only keep on growing if you vote daily!";
r_text[3] = "Purchasing VIP in the forums helps with the monthly server costs.";
r_text[4] = "{hotelName} Is a new and developing RP!";
window.setInterval(function(){
var i = Math.floor(4 * Math.random())
document.write(r_text[i]);
var random = r_text[1];
}, 5000);
</script>
</div>
</div>
<div id="subnavi-search">
<div id="subnavi-search-upper">
<ul id="subnavi-search-links">
<li>Sign Out</li>
I am not sure if this is what you are looking for but here it is:
This script will run every time you reload the page. IF you need it to work in a different way just update your question and i will update my script.
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var r_text = new Array();
r_text[0] = "Hello";
r_text[1] = "Test";
r_text[2] = "We are the lions";
r_text[3] = "Fight";
r_text[4] = "Switch!";
window.setInterval(function(){
var i = Math.floor(5 * Math.random())
var random = r_text[i];
$('#r_text').html(random);
}, 5000); // you can change the interval here
The HTML part
<div id="r_text"></div>
Check this out here
Update
Change your Math.floor to count to 5 because your array has 5 elements in it not 4
Update 2 Your file should look like something like this
<!Document html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var r_text = new Array();
r_text[0] = "Hello";
r_text[1] = "Test";
r_text[2] = "We are the lions";
r_text[3] = "Fight";
r_text[4] = "Switch!";
window.setInterval(function(){
var i = Math.floor(5 * Math.random())
var random = r_text[i];
$('#r_text').html(random);
}, 5000); // you can change the interval here
</script>
</head>
<body>
//Add your html/php code here and pick a place where to show the response of your function. Something like <div id="r_text"></div>
</body>
</html>

Need Help: Make the quiz random [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });

How can I save variables on refresh?

<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)
I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.
you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.

Categories