How to pass value between functions? - javascript

i'm creating a very simple Santa's game for my friends. So the logic is again very simple. Given a list of names, user need to insert his/her name and whenever the button is clicked, a random name will pick up from the list and display as result.
I have two small problems:
I can find and display the random name form the list but I cannot pass in the luckyName function and display it if is not the same of the user's name.
In case the name of the current user is the same of the picked up name, I 'm not sure how to or what's the best way to pick up another name. So far I just call again the pickRandomName function.
Html:
<h3>Santa ask: Who are you kid?</h3>
<section>
<input type="text" placeholder="YOUR name bitte, not time for joke.." id='santaName'/>
<div id="go">Go</div>
</section>
js:
var nameList = [
'gio',
'anna',
'chiara',
'ella',
'sarah',
'sara'
];
$(document).ready(function(){
pickRandomName();
luckyName();
});
var luckyName = function(randomName){
var section = $('section');
$('section').on('click', '#go', function(){
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if( currentSanta != randomName){
console.log(randomName);
$('section').append(randomName);
} else {
//pick up another random name
pickRandomName(randomName);
console.log(randomName);
}
});
};
var pickRandomName = function(randomName){
var randomName = nameList[Math.floor(Math.random() * nameList.length)];
console.log(randomName);
};
and here the fiddle:
http://jsfiddle.net/anaketa/r9morh87/1/

Here is the working fiddle for your code.
$(document).ready(function(){
window.randomName =pickRandomName(nameList);/*we have created an global variable which will store randomName*/
luckyName(nameList);
});
function luckyName(nameList){
var section = $('section');
$('section').on('click', '#go', function(){
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if( currentSanta != window.randomName){
console.log(window.randomName);
$('section').append(window.randomName);
}
else {
//pick up another random name
window.randomName = pickRandomName(nameList);/*It will change the global var window.randomName value*/
console.log(x);
}
});
}
function pickRandomName(randomName){
var randomName1 = nameList[Math.floor(Math.random() * nameList.length)];
console.log(randomName1);
return randomName1;
};
I am passing the value between functions by using window.randomName (Learn more about different kinds of variable here).
By defining window.randomName we have attached a property to window, like "window.location", which can accessed by all the functions whenever and wherever they want without the need to passing the argument to function again and again and also the function can change it's value so whenever we need to pass a variable to different function this is one way to do it.

Try this,
var nameList = [
'gio',
'anna',
'chiara',
'ella',
'sarah',
'sara'
];
$(document).ready(function() {
var randomName = nameList[Math.floor(Math.random() * nameList.length)];
//console.log( nameList[Math.floor(Math.random() * nameList.length)]);
$('#go').on('click', function() {
luckyName(randomName);
});
});
var luckyName = function(randomName) {
var section = $('section');
$('section').on('click', '#go', function() {
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if (currentSanta != randomName) {
console.log(randomName);
$('section').append(randomName);
} else {
//pick up another random name
pickRandomName(randomName);
console.log(randomName);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Santa ask: Who are you kid?</h3>
<section>
<input type="text" placeholder="YOUR name" id='santaName' />
<div id="go">Go</div>
</section>

Related

Reusing Javascript code without repasting it again and again

I have the below code, which looks for the text "UID" and changes it to "UID *"
On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?
<script type="text/javascript">
//Mark UID as Mandatory
var CFN = "UID";
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(CFN, 'UID *'));
});
}
</script>
EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;
<script type="text/javascript">
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.append(MandatoryCFs, ' *'));
});
}
</script>
Replace multiple strings by using list of| Regex
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
});
}
or like this if you don't need to the replaced strings to be dynamic:
text.replace(/UID|Description/g, '$& *')

JavaScript - Displaying saved comment the name and comment are displayed next to each other rather than on top?

I want the JS to be able to save the comment of the inputted name and comment and for it to be displayed after clicking the Save Comment button underneath the Comments at the bottom.
It does that but the name and the comment are side by side instead of on top of each other and looks confusing
// utility functions for localstorage
function setObject(key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
}
function getObject(key) {
var storage = window.localStorage,
value = storage.getItem(key);
return value && JSON.parse(value);
}
function clearStorage() {
window.localStorage.clear();
}
// Clear inputfields and localstorage
function clearComment(){
$('#txt1').val('');
$('#namebox').val('');
clearStorage();
}
function saveComment(){
var cText = $('#txt1').val(),
cName = $('#namebox').val(),
cmtList = getObject('cmtlist');
if (cmtList){
cmtList.push({name: cName, text: cText});
setObject('cmtlist', cmtList);
}else{ //Add a comment
setObject('cmtlist', [{name: cName, text: cText}]);
}
bindCmt();
}
function bindCmt(){
var cmtListElement = $('#cmtlist'),
cmtList = getObject('cmtlist');
//Out with the old
cmtListElement.empty();
//And in with the new
$.each(cmtList, function(i, k){
cmtListElement.append( $('<p><span>'+ k.name +'</span>'+ k.text +'</p>') );
});
}
//Get the comments on page ready
$(function(){
bindCmt();
});
it looks like this:
You could add an html break <br> to the line below:
cmtListElement.append( $('<p><span>'+ k.name +'</span><br>'+ k.text +'</p>') );

Auto Form Post With Url Function

I have a problem with javascript. I use google api and it contains ajax. The problem here is that, I need to catch values from URL like http://examplesite.com/index.php?s=some+values . I need to search values automatically. I try to do this for along time. However, I couldn't. How can I do this ?
This is my submit form:
<form id="searchForm" method="post">
<fieldset style="width: 520; height: 68">
<input id="s" type="text" name="s" />
<input type="submit" value="Submit" id="submitButton" />
Here is my javascript codes:
$(document).ready(function(){
var config = {
siteURL : 'stackoverflow.com', // Change this to your site
searchSite : true,
type : 'web',
append : false,
perPage : 8, // A maximum of 8 is allowed by Google
page : 0 // The start page
}
// The small arrow that marks the active search icon:
var arrow = $('<span>',{className:'arrow'}).appendTo('ul.icons');
$('ul.icons li').click(function(){
var el = $(this);
if(el.hasClass('active')){
// The icon is already active, exit
return false;
}
el.siblings().removeClass('active');
el.addClass('active');
// Move the arrow below this icon
arrow.stop().animate({
left : el.position().left,
marginLeft : (el.width()/2)-4
});
// Set the search type
config.type = el.attr('data-searchType');
$('#more').fadeOut();
});
// Adding the site domain as a label for the first radio button:
$('#siteNameLabel').append(' '+config.siteURL);
// Marking the Search tutorialzine.com radio as active:
$('#searchSite').click();
// Marking the web search icon as active:
$('li.web').click();
// Focusing the input text box:
$('#s').focus();
$('#searchForm').submit(function(){
googleSearch();
return false;
});
$('#searchSite,#searchWeb').change(function(){
// Listening for a click on one of the radio buttons.
// config.searchSite is either true or false.
config.searchSite = this.id == 'searchSite';
});
function googleSearch(settings){
// If no parameters are supplied to the function,
// it takes its defaults from the config object above:
settings = $.extend({},config,settings);
settings.term = settings.term || $('#s').val();
if(settings.searchSite){
// Using the Google site:example.com to limit the search to a
// specific domain:
settings.term = 'site:'+settings.siteURL+' '+settings.term;
}
// URL of Google's AJAX search API
var apiURL = 'http://ajax.googleapis.com/ajax/services/search/'+settings.type+'?v=1.0&callback=?';
var resultsDiv = $('#resultsDiv');
$.getJSON(apiURL,{q:settings.term,rsz:settings.perPage,start:settings.page*settings.perPage},function(r){
var results = r.responseData.results;
$('#more').remove();
if(results.length){
// If results were returned, add them to a pageContainer div,
// after which append them to the #resultsDiv:
var pageContainer = $('<div>',{className:'pageContainer'});
for(var i=0;i<results.length;i++){
// Creating a new result object and firing its toString method:
pageContainer.append(new result(results[i]) + '');
}
if(!settings.append){
// This is executed when running a new search,
// instead of clicking on the More button:
resultsDiv.empty();
}
pageContainer.append('<div class="clear"></div>')
.hide().appendTo(resultsDiv)
.fadeIn('slow');
var cursor = r.responseData.cursor;
// Checking if there are more pages with results,
// and deciding whether to show the More button:
if( +cursor.estimatedResultCount > (settings.page+1)*settings.perPage){
$('<div>',{id:'more'}).appendTo(resultsDiv).click(function(){
googleSearch({append:true,page:settings.page+1});
$(this).fadeOut();
});
}
}
else {
// No results were found for this search.
resultsDiv.empty();
$('<p>',{className:'notFound',html:'No Results Were Found!'}).hide().appendTo(resultsDiv).fadeIn();
}
});
}
function result(r){
// This is class definition. Object of this class are created for
// each result. The markup is generated by the .toString() method.
var arr = [];
// GsearchResultClass is passed by the google API
switch(r.GsearchResultClass){
case 'GwebSearch':
arr = [
'<div class="webResult">',
'<h2>',r.title,'</h2>',
'<p>',r.content,'</p>',
'',r.visibleUrl,'',
'</div>'
];
}
// The toString method.
this.toString = function(){
return arr.join('');
}
}
});
Look at my answer here. As you can see, it is not too difficult to set a get parameter. Now, I will show you how you can get a get parameter:
function getGetParameter(paramName)
{
var url = window.location.href;
if (url.indexOf(paramName + "=") >= 0)
{
var returnValue = url.substring(url.indexOf(paramName + "="));
if (returnValue.indexOf("&") >= 0)
{
returnValue = returnValue.substring(0, returnValue.indexOf("&"));
}
return returnValue.substring(returnValue.indexOf("=") + 1);
}
return null;
}
As about searching for values automatically, you need to specify what and how would you like to search for, as this can be needed/done literally in infinitely many ways.
maybe this is the problem: you're trying to use an API and it's no longer avaiable.
Object {responseData: null, responseDetails: "This API is no longer available.", responseStatus: 403}
More information here: https://developers.google.com/image-search/v1/jsondevguide
Now, I'm trying to find a migration to version 2.

Undefined function error for javascript function

Here is my code, I don't understand what's wrong.
<script type="text/jquery">
function gettotalAdult()
{
//Assume form with id="fsd-bucket-calc"
var theForm = document.forms["fsd-bucket-calc"];
//Get a reference to the # of Adults & Children
var quantity = theForm.elements["totalAdult"];
var caloriesAdult = theForm.elements["caloriesAdult"];
var adultcalTotal=0;
//If the totalAdult is not blank
if(totalAdult.value!="")
{
adultcalTotal = parseInt(totalAdult.value)*parseInt(caloriesAdult.value);
}
return adultcalTotal;
}
function gettotalChild()
{
//Assume form with id="fsd-bucket-calc"
var theForm = document.forms["fsd-bucket-calc"];
//Get a reference to the # of Children
var totalChild = theForm.elements["totalChild"];
var caloriesChild = theForm.elements["caloriesChild"];
var childcalTotal=0;
//If the totalChild is not blank
if(totalChild.value!="")
{
childcalTotal = parseInt(totalChild.value)*parseInt(caloriesChild.value);
}
return childcalTotal;
}
function gettotalCalories()
{
//Here we get the total calories by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalCalories = gettotalAdult() + gettotalChild();
//display the result
document.getElementById('total-req-cal').innerHTML = "The total required calories are "+totalCalories;
}
</script>
This is my HTML:
<input type="text" name="totalAdult" id="totalAdult" onkeyup="gettotalCalories()" />
This is my error:
gettotalCalories is not defined
If it helps, the script is in the head of a WordPress page. Does anyone see what I'm doing wrong?
You have <script type="text/jquery"> you may need <script type="text/javascript"> instead.

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories