I am calling a function using onClick inside button. The called function is inside an object and it is getting called each second using setTimeout. But callback function is not getting called by setTimeout and works for just first call.
if i do not use object and use a encapsulating function that returns startPomadoro function, then its working.
###HTML Code ##########
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
### JS COde
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText:'',
startPomodoro: function(){
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if(this.countPomadoro<pomadoroTimeInMinutes){
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
this.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
this.countPomadoro++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
if(this.countBreak<breakInMnutes){
var minutesLeftBreak = this.breakInMinutes - this.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
this.countBreak++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
this.currentTimerText=" Break Time is UP. ";
this.displayPomadoro();
}
}
},
displayPomadoro: function(){
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent=this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
You had a problem with this not being what you think, when function was called from setTimeout. Try something like this:
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText: '',
startPomodoro: function() {
var that = this;
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if (this.countPomadoro < pomadoroTimeInMinutes) {
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
that.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
that.countPomadoro++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
if (that.countBreak < breakInMinutes) {
var minutesLeftBreak = that.breakInMinutes - that.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
that.countBreak++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
that.currentTimerText = " Break Time is UP. ";
that.displayPomadoro();
}
}
},
displayPomadoro: function() {
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent = this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
PS. You also had a typo breakInMnutes instead of breakInMinutes.
I have solved this problem by moving away from jquery , and simply
setting event handler on divs by wrapping each image inside one div using
JavaScript. Below is the sample code.
//code
handler.divs.forEach(function(div){
var img = document.getElementById(div);
img.onclick = function(){
var id = parseInt(img.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" div clicked " + id + " u p " + userPattern);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" if ");
handleWrongInput();
} else if(userPattern.length === simonGame.PATTERN.length){
setTimeout(function(){simonGame.patternGen({result:"success"})},1200);
}
}
});
console.log(" up " + userPattern + " SGP " + simonGame.PATTERN);
Related
Question: I have a function called
play() {
//Many lines of code here
}
now I have a button in index.html, having a class="playButton"
I want to run the function play(); as soon as the button with class="playButton" is pressed.
Therefore, I wrote following code inside index.js
document.querySelector.(".playButton").addEventListener("click", play () );
What is the correct way to put play function after "click", in eventListener?
Abbreviated source from repository linked to by OP in comments: armaghan05/rollthedice
var p1Name = "P1";//prompt("Please enter 1st player's name");
var p2Name = "P2";//prompt("Please enter 2nd player's name");
document.querySelector(".player1").innerHTML = p1Name;
document.querySelector(".player2").innerHTML = p2Name;
function play() {
// FOR DICE ONE:
var randomNumber1 = (Math.floor(Math.random() * 6) + 1);
var randomImageName1 = "dice" + randomNumber1 + ".png";
var randomSource1 = "images/" + randomImageName1;
document.querySelector(".img1").innerHTML = randomSource1;
// FOR DICE TWO:
var randomNumber2 = (Math.ceil(Math.random() * 6));
var randomImageName2 = "dice" + randomNumber2 + ".png";
var randomSource2 = "images/" + randomImageName2;
document.querySelector(".img2").innerHTML = randomSource2;
// MESSAGE TO PLAYERS:
if (randomNumber1 > randomNumber2) {
document.querySelector(".mainHeading").innerHTML = p1Name + " wins π";
document.querySelector(".player1").innerHTML = p1Name + "ππ π";
document.querySelector(".player2").innerHTML = p2Name + "π«ππ½";
} else if (randomNumber1 < randomNumber2) {
document.querySelector(".mainHeading").innerHTML = p2Name + " wins π"
document.querySelector(".player2").innerHTML = p2Name + "ππ π";
document.querySelector(".player1").innerHTML = p1Name + "π«ππ½";
} else {
document.querySelector(".mainHeading").innerHTML = "ScheiΓe! π©! It is a draw π";
document.querySelector(".player1").innerHTML = p1Name;
document.querySelector(".player2").innerHTML = p2Name;
}
}
<div class="container">
<h1 class="mainHeading bigHeading">Welcome !!! </h1>
<div class="dice">
<p class="player1">Player 1</p>
<div class="img1"></div>
</div>
<div class="dice">
<p class="player2">Player 2</p>
<div class="img2"></div>
</div>
</div>
<div class="playButton">
<button class="playButton" type="button" name="Play" onclick="play();">Play</button>
</div>
Like #zero298 suggested, their is a big differences between
document.querySelector.(".playButton").addEventListener("click", play () );
and the similar:
document.querySelector.(".playButton").addEventListener("click", play );
The () are what tell your code to execute this function, so in the first example you pass the return value of the function but instead what to pass the function itself, using an intermediate variable may help understand:
const playResult = play ();
document.querySelector.(".playButton").addEventListener("click", playResult);
// vs:
const playHandler = play; // the function itself !
document.querySelector.(".playButton").addEventListener("click", playHandler);
As stated, you need to just pass play to the event listener. Do this after you define play. Directly after you define function play() {...}, query for the element and attach the listener:
document.querySelector(".playButton").addEventListener("click", play);
In context:
var p1Name = "P1";//prompt("Please enter 1st player's name");
var p2Name = "P2";//prompt("Please enter 2nd player's name");
document.querySelector(".player1").innerHTML = p1Name;
document.querySelector(".player2").innerHTML = p2Name;
function play() {
// FOR DICE ONE:
var randomNumber1 = (Math.floor(Math.random() * 6) + 1);
var randomImageName1 = "dice" + randomNumber1 + ".png";
var randomSource1 = "images/" + randomImageName1;
document.querySelector(".img1").innerHTML = randomSource1;
// FOR DICE TWO:
var randomNumber2 = (Math.ceil(Math.random() * 6));
var randomImageName2 = "dice" + randomNumber2 + ".png";
var randomSource2 = "images/" + randomImageName2;
document.querySelector(".img2").innerHTML = randomSource2;
// MESSAGE TO PLAYERS:
if (randomNumber1 > randomNumber2) {
document.querySelector(".mainHeading").innerHTML = p1Name + " wins π";
document.querySelector(".player1").innerHTML = p1Name + "ππ π";
document.querySelector(".player2").innerHTML = p2Name + "π«ππ½";
} else if (randomNumber1 < randomNumber2) {
document.querySelector(".mainHeading").innerHTML = p2Name + " wins π"
document.querySelector(".player2").innerHTML = p2Name + "ππ π";
document.querySelector(".player1").innerHTML = p1Name + "π«ππ½";
} else {
document.querySelector(".mainHeading").innerHTML = "ScheiΓe! π©! It is a draw π";
document.querySelector(".player1").innerHTML = p1Name;
document.querySelector(".player2").innerHTML = p2Name;
}
}
document.querySelector(".playButton").addEventListener("click", play);
<div class="container">
<h1 class="mainHeading bigHeading">Welcome !!! </h1>
<div class="dice">
<p class="player1">Player 1</p>
<div class="img1"></div>
</div>
<div class="dice">
<p class="player2">Player 2</p>
<div class="img2"></div>
</div>
</div>
<div class="playButton">
<button class="playButton" type="button" name="Play">Play</button>
</div>
I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
I'm currently working on a weather site. I want to get the user input into a variable that changes the current city. Hope someone of you can help me.
var userInput = "London";
function changeValue() {
userInput = document.getElementById("user_Input").value;
document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
}
window.onload = function() {
var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var iconCode = myObj.list[0].weather[0].id;
var directions = myObj.list[0].deg;
for (var i = 0; i < 7; i++) {
document.getElementById("day" + i).innerHTML = Math.round(myObj.list[i].temp.day) + "Β°";
document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
document.getElementById("direction").innerHTML = directions;
}
}
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
};
<article>
<input id="user_Input" type="text" placeholder="Ortsuchen...">
<button id="submit" onclick="changeValue()">Submit</button>
<span id="location">Unknown</span>
</article>
<section>
<div>
<div><span id="day0" class="ml:.25r fs:6r">0</span></div>
<div><span id="wochentage">0</span></div>
</div>
<div>
<img id="icon0">
</div>
<div>
<span id="wind">0</span><span id="direction"></span><span></span>
</div>
<div>
<span id="humidity">0</span><span>%</span>
</div>
</section>
location is getting updated after hitting the submit button. But the value of the variable doesn't change. I've already looked around stackoverflow and other sites but didn't find any solution that works for me.
1st : Your request will only run on page load . you need to run that again after user change the userInput .so make it as a function and call it every time of userInput change like this .
var userInput = "London";
function changeValue() {
userInput = document.getElementById("user_Input").value;
document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
ajax_call();
}
function ajax_call(){
var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var iconCode = myObj.list[0].weather[0].id;
var directions = myObj.list[0].deg;
for (var i = 0; i < 7; i++) {
document.getElementById("day" + i).innerHTML = Math.round(myObj.list[i].temp.day) + "Β°";
document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
document.getElementById("direction").innerHTML = directions;
}
}
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
}
window.onload = function() {
ajax_call();
};
<article>
<input id="user_Input" type="text" placeholder="Ortsuchen...">
<button id="submit" onclick="changeValue()">Submit</button>
<span id="location">Unknown</span>
</article>
<section>
<div>
<div><span id="day0" class="ml:.25r fs:6r">0</span></div>
<div><span id="wochentage">0</span></div>
</div>
<div>
<img id="icon0">
</div>
<div>
<span id="wind">0</span><span id="direction"></span><span></span>
</div>
<div>
<span id="humidity">0</span><span>%</span>
</div>
</section>
I have these functions:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).find('.comments-form-' + guid).hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
$(this).find('.comments-form-' + showGuid).show();
var showGuid = $(this).attr('rel');
loadShowingsComments(showGuid);
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
function loadShowingsComments(guid) {
var commentTextArea = "#comments-form-" + guid;
var commentDisplay = ".spanComments" + guid;
var curComment = $(commentDisplay).text();
var element = "#comments-form-" + guid;
$(element).slideDown();
}
<script>
function showComments() {
var comments = document.querySelectorAll(".spanComments");
for (var i = 0; i < comments.length; i++) {
comments[i].innerHTML = "This is comment #" + i;
}
}
</script>
View Comments
Those functions should grab the information from my controller (it's hooked up correctly. I've stepped through that and it has populated the right information) and place them in my span:
<tr class="p_la" id="comments-form-#currentShowing.ShowingGUID" style="display:none;">
<td colspan="4" style="border-right:5px solid #DDDDDD;">
<form action="" method="post">
<span class="spanComments" cols="100" rows="5">#string.Format("{0} / {1}", #currentShowing.Comments.DateAdded, #currentShowing.Comments.CommentsValue)</span>
<br />
Close
</form>
</td>
</tr>
Unfortunately, when I click on my hyperlink, it only populates the first span with the first span's information. Works great for the first span but when you click on the hyperlink in the second, third, fourth, etc item, they will only open up the first span with the first span's information.
The code should populate each successive span with its own information.
My JQuery was off. It needed this to be changed:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).parent("form").parent("td").parent("tr").hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
var showGuid = $(this).attr('rel');
$(this).parent("td").parent("tr").next('#comments-form-' + showGuid).show();
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
when i have to open this page i want to display all contacts in phone with out click on any button.
Here myFunction() displays all contacts.
I have to call `myFunction()`, in this code. I dont know where to call this function. Help me
var ar1 = new Array;
var ar2 = new Array;
var name, number;
var counter = 1;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
filter = [ "displayName", "phoneNumbers" ];
navigator.contacts.find(filter, onSuccess, onError, options);
}
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
name = contacts[i].displayName;
number = contacts[i].phoneNumbers[j].value;
ar1.push(name);
ar2.push(number);
// here i called myFunction(), but it's displaying one contact in multiple times
}
// here i called myFunction(), but it's displaying one contact in multiple times
}
// Here i called myFunction(), the function is not calling
}
function onError(contactError) {
alert('onError!');
}
// where to call this function
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />selectAll</br> <br />
<br /> <br />
</div>
</div>
</body>
</html>
I cannot catch what you want exactly.
if you want to generating phonenumber checkbox list when your app starts,
just call myFunction() in end of onSuccess() callback.
if you want another time, you should define a event handler that you want like below.
$("#PhonenumberListButton" ).click( function() { myFunction(); } );
and your code can occur index exception during loop.
Let's think about below.
each contact has 1 name but has 1 or more phone numbers
your code pushes each name into ar1 and also pushes each phone numbers of contact into ar2
so ar2.length can be greater than ar1.length
your generating display code use ar2.length for loop. it should make exception if any contact has 2 or more phonenumbers.
This's a reason of stop your loop in onSuccess().
Fixed Code
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
name = contacts[i].displayName;
ar1.push(name);
ar2[i] = []; // array for multiple phone#.
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
number = contacts[i].phoneNumbers[j].value;
ar2[i].push(number);
}
}
myFunction(); // display phone numbers
}
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
if ( ar2[i].length ) { // avoid none phone# exception
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i][0] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
}