What is the purpose of this JavaScript code? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I was poking around with inspect element and came across this:
NumberOfDivsToRandomDisplay = 10;
var CookieName = 'DivRamdomValueCookie';
function DisplayRandomDiv() {
var r = Math.ceil(Math.random() * NumberOfDivsToRandomDisplay);
if (NumberOfDivsToRandomDisplay > 1) {
var ck = 0;
var cookiebegin = document.cookie.indexOf(CookieName + "=");
if (cookiebegin > -1) {
cookiebegin += 1 + CookieName.length;
cookieend = document.cookie.indexOf(";", cookiebegin);
if (cookieend < cookiebegin) {
cookieend = document.cookie.length;
}
ck = parseInt(document.cookie.substring(cookiebegin, cookieend));
}
while (r == ck) {
r = Math.ceil(Math.random() * NumberOfDivsToRandomDisplay);
}
document.cookie = CookieName + "=" + r;
}
for (var i = 1; i <= NumberOfDivsToRandomDisplay; i++) {
document.getElementById("randomdiv" + i).style.display = "none";
}
document.getElementById("randomdiv" + r).style.display = "block";
}
DisplayRandomDiv();
What is its purpose? Just curious, thanks :)

This code assumes you have div's with ID's "randomdiv1", "randomdiv2" etc.
It then reads the cookie named DivRamdomValueCookie. If it's present, it contains an integer value which will be the ID of the div currently shown ("randomdiv" + value of the cookie).
Then, it will hide all the divs, and then show one of the divs, different from the div whose ID was stored in the cookie. If the cookie was not present, it will display random div.
This script has a hard-coded number of div's in a NumberOfDivsToRandomDisplay variable.

toggling of divs that also stores a particular div state for some time.
http://ipankaj.net/how-to-display-multiple-testimonials-randomly-on-your-website/

Related

Why Random variable is only returning 1 character [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 11 months ago.
Improve this question
Hey guys im trying to generate a random password using upper and lowercase keys + numbers. the code seems to work but instead of returning 20 characters its instead returning only 1. The return seems random.
The element should be replaced why the random password every time the button is clicked.
HTML
<button id = "button5" onclick = "password()">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
This is the Javascript
function password (length ) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here
for (var i = 0; <length ; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() *
chara.length));
return ranpassword;
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
console.log(password(20));
}
whenver the button is clicked, one random letter is returned in console.log and i cant seem to understand why ? Can anyone tell me why?
Any help would be great . Thanks :)
You did some mistake. Try this code,
function password (length) {
let ranpassword = "",
chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ",
charalength = chara.length;
for (var i = 0; i<length ; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() *
chara.length));
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick="password(20)">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
Aside from your password function implementation partly wrong, you are not passing a length to password() function in your onclick handler.
You need to pass the length as well like password(20):
<button id = "button5" onclick = "password(20)">Generate password </button>
as #Locke said, your for loop syntax is incorrect, as You are missing i in the comparison. Other than that, you code is flooded with typos. You didn't close the for loop, and you didn't need to return ranpassword. Now your code works, notice that the number I put as a parameter in the onclick in the HTML is the length your password will be. Also, instead of using .chatAt, I generate a random number and add it to ranpassword. For example: The for loop gets chara[4], so randpassword has chara's 5th letter.
function password(length) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var charalength = chara.length // there is an outside variable defining charalength = ""; I could not include that here
for (var i = 0; i < length; i++) {
ranpassword += chara[(Math.floor(Math.random() *
chara.length))];
}
document.getElementById("p4").innerHTML = "hello there " + ranpassword;
}
<button id = "button5" onclick = "password(4)">Generate password </button>
<p4 id = "p4" > Your password will apear here </p4>
I have fixed the problem
function password(length) {
var ranpassword = "";
var chara = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var charalength = chara.length;
for (var i = 0; i < length; i++) {
ranpassword += chara.charAt(Math.floor(Math.random() * chara.length));
}
return ranpassword;
}
console.log(password(5));
you were returning the password form the loop so it was returning a single character

Need help to understand Vue.js function [closed]

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 3 years ago.
Improve this question
I have an assignment to make calculator using vue.js.
Much of it works, I'm confused about how to implement the '=' function.
I found this piece of code in an article that does something similar but I don't understand what it does. Can someone explain it?
https://scotch.io/tutorials/build-a-scientific-calculator-with-vuejs
I found this Piece of code:
if ((app.current).indexOf("^") > -1) {
var base = (app.current).slice(0, (app.current).indexOf("^"));
var exponent = (app.current).slice((app.current).indexOf("^") + 1);
app.current = eval("Math.pow(" + base + "," + exponent + ")");
} else {
app.current =app.current
}
Can someone please explain what the above function does, line-by-line?
// checks if app.current have '^' by getting the index
// if the method indexOf doesn't find anything it return -1
if (app.current.indexOf('^') > -1) {
// gets the first element till the index where it found '^'
var base = app.current.slice(0, app.current.indexOf('^'));
// gets the number after the 'ˆ'
var exponent = app.current.slice(app.current.indexOf('^') + 1);
// eval is evil
// it gets the string and transfoms into valid code
// wich means to do the operation
app.current = eval('Math.pow(' + base + ',' + exponent + ')');
} else {
// if it doesn't find the index it keeps the same value
app.current = app.current;
}
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

Need to display a character '-' based on a string length in Javascript [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 6 years ago.
Improve this question
I am trying to make a hangman game and what I want to do is make the minus/dash symbol '-' appear the number of times for the string length of the randomly chosen word from an array.
So far what I have is:
HTML:
<h1>Hangman</h1>
<br>
<br>
<div style="margin-left: 100px;">
<p id = "word"> </p>
<div id="image"></div>
</div>
then in my js file I have:
var randomWords = ['rock','paper','scissors'];
document.onkeyup = function(event) {
var chosenWord = randomWords[Math.floor(Math.random()*randomWords.length)];
// var blankLines = "";//(1)
for (int x = 0; x < chosenWord.length; x++)
{
// blankLines += '- '; //(1)
// document.getElementById("word").innerHTML = blankLines;
// document.getElementById("word").innerHTML = ;
}
//document.getElementById("word").innerHTML = blankLines;//(1)
None of the commented out methods worked. The (1) means that these lines go together when I tried it out.
Try this,
var dash='-', x="",chosenWord="sdsjdj";
for (var i = 0; i < chosenWord.length; i++)
{
if(i!=(chosenWord.length-1)) {
x=x+dash+" ";
}
else {
x=x+dash;
}
}
console.log(x);
If you are not targeting ES6, this is just as easy:
chosenWord.replace(/./g, '-')
If you are targeting ES6 you can simply use the repeat function:
"-".repeat(chosenWord.length);
If you are targeting non-ES6 (older browsers), you can do a "hack" like below:
Array(chosenWord.length).join("-")
Or you can use more descriptive code like this:
var dashes = "";
for (var i = 0; i < chosenWord.length; i++) {
dashes = dashes + "-";
}

search() javascript doesn't work if first character there isn't in the string [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 6 years ago.
Improve this question
Hello I know that search() in javascript doesn't work (returns -1) if first charachter does not exist in the string...
$('#search-vulc').on('keyup', function() {
var textinsert = ($(this).val()).toLowerCase();
var nome_search = "home";
if (nome_search.search(textinsert) != -1) {
alert('ok');
}
else {
alert('not');
}
});
And so in this example if we write "x home", returns -1.
But is there a way to "solve" this problem ?
in short, if i write "x home" anyway there is the word home...
I would like a method that in this case doesn't return -1
You're searching for "x home" in "home".
Thus it is returning -1.
if (nome_search.search(textinsert) != -1)
Should be
if (textinsert.search(nome_search) != -1)
Is this nome_search.search(textinsert) simply backwards? textinsert.search(nome_search)
Refactored code:
function getStringPostion(re, str) {
var midstring;
var position = str.search(re);
midstring=(position != -1) ? ' contains ':' does not contain ';
console.log(str + midstring + re);
console.log(position );
return position;
}
var foundAtPosition = getStringPostion("home","x home");
Iterating trough all the inserted strings might do:
var f = function(re) {
var textinsert = ($(this).val()).toLowerCase().split(" ");
var nome_search = "home";
var result = 0;
for (var i = 0; i<textinsert.length; i++){
console.log(textinsert[i]);
if (nome_search.search(textinsert[i]) != -1) result++;
}
return result > 0 ? alert('ok') : alert('not') ;
};
as long as they are separated by spaces like in your example.

Some <div>s with a for loop [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 9 years ago.
Improve this question
I have a for loop and I want to create many <div>s with it.
I want to give the <div>s am ID from a varible.
Here's the code:
var text = $("#cont").text();
count = 1;
for (var i = 1; i <= 10; i++) {
text += "<div class='ball' id='ball'" + count + "></div><br />";
count++;
}
You've messed up your quotes:
text += "<div class='ball' id='ball" + count + "'></div><br />";
Your code had the single quote wrong and produced this:
<div class='ball' id='ball'5>
The number needs to be inside.
I'm a bit confused what your question is: It looks like you've already got the logic to do what you've specified.
That said, I see a probable error that may be confusing you: You're closing the single-quote on id='ball' before you concatenate the count variable. That will result in the div element not having that number as part of its id. Here's a corrected version of the code:
var text = $("#cont").text();
count = 1;
for (var i = 1; i <= 10; i++) {
text += "<div class='ball' id='ball" + count + "'></div><br />";
count++;
}

Categories

Resources