Waiting for user input with jQuery and Javascript - javascript

I am trying to wait to take the user's input (clicking a button) before continuing with the program. A simplified version of the code is this:
$(document).ready(function(){
var answer = $(".question").on("click", "button", takeAnswer);
alert(answer);
});
//Code to set the next question once the user has answered the previous question
function takeAnswer(){
var answer = ($(".question button").data("answer"));
alert(answer);
return answer;
}
The HTML body simply contains this:
<p class="question"><button data-answer="1">Push me</button></p>
On loading, the HTML alerts [object Object]. once you click the button, the page alerts 1 as it is supposed to. I think the problem is that the return line is executing without awaiting the user's click. My research suggests that I need to use a callback function (there are several discussions on waiting for user input), but I'm confused because I thought that putting the takeAnswer code in a separate function would keep the subsequent code from executing.
For further context, my goal is to ask a series of choose-your-own-adventure style questions, changing later questions based on earlier user input. I intend to use jQuery to remove the previous question and place the new question, according to logic within the JavaScript file. Edit 1: I should also mention that I am pretty new to this and am trying to teach myself (if that's not already obvious).
Edit 3: Here is the full context in JSFiddle. http://jsfiddle.net/T7VhC/ The problem is the "undefined" error arising from line 144 of the JS.
Edit 2:
Eventually I want to add other buttons and capture which button was clicked. Here is a simplified example of another (dysfunctional because, I think, there is no callback) attempt to implement what I'm doing:
function takeAnswer(){
$(document).ready(function(){
$(".question").on("click", "button", function(){
return $(this).data("answer");
});
});
}
alert(takeAnswer());
HTML:
<body>
<p class="question"><button data-answer="1">Push me</button></p>
<p class="question"><button data-answer="2">Or push me</button></p>
</body>
Thanks.

For complete code, you could use:
$(document).ready(function(){
$(".question").on("click", "button", takeAnswer);
});
//Code to set the next question once the user has answered the previous question
$(takeAnswer);
function takeAnswer(){
var answer = $(".question button").data("answer");
alert(answer);
}

Try following
<script>
$(document).ready(function(){
var answer = $(".question").on("click", "button", takeAnswer);
takeAnswer();
});
//Code to set the next question once the user has answered the previous question
function takeAnswer(){
var answer = ($(".question button").data("answer"));
alert(answer);
return answer;
}
</script>

Related

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

Div does not refresh when last character is deleted from input

I'm currently making a search function using a onkeyup="Search();" like this:
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
The function for it is:
<script type="text/javascript">
function Search() {
var inputVal = $('#IDsearch').val();
$.post('searchTest.php', {postname: inputVal},
function (data) {
$('#IDsearch').val(data)
});
$('#divRefresh').load('searchTest.php');
}
</script>
Yes, I am using the same file to both put the value in a php $_SESSION['value']; AND to store the new div data. That's no problem, it works, it does fine.
But when I delete my last character from my search box, I need to press backspace twice in order for my div to update.
Say I had a textbox with "a" in it. I will press backspace to update the a, and nothing will happen. Once I press backspace again, my div will update and post all the original values again.
Am I missing something obvious?
It's supposed to work the same way http://www.datatables.net/ does.
I have asked a question about this program before, but not about this issue, I hope it's not a problem.
I would go throught $("#IDsearch").keyup(function(){});
Tried your code with the function and didn't work, even with $("#divRefresh").html(theInputOfYours); The other way I mention to you works perfectly, even with backspace.
$(document).ready(function() {
$("#IDsearch").keyup(function() {
var value = $(this).val();
var posting = $.post("your_php_file.php", {val: value})
posting.done(function( data ) {
$( "#divRefresh" ).html(data);
});
});
});
The posting is a very basic example I can give, I use to go with $.ajax() function
Unfortunately, the behavior of keyup/keypress/keydown can be finicky sometimes, especially across different browsers.
A possible solution to ensure changes are tracked would be a listener that would track changes via a setInterval function that runs at an interval you specify.

YUI jQuery calling function on page load

is there any one who is familiar with YUI jQuery frame work ?? i need very little help
please take the look at below code
It works perfect but the inputClick() is called when i press any button left or right but i dont want button, i want to call function when page loads means automatically
please help me some one.
in short I want to call inputclick(e){......} automatically when page load
i heard about domready function which is same like JQuery's document.ready function
so how should i call inputClick(e)??
please take look at this ::
<section id="btns">
<p>
<input type="button" value="Left">
<input type="button" value="Right">
</p>
</selection>
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
<script>
document.querySelector('#btns').addEventListener("click", inputClick, false);
function inputClick(e){
var a = e.target.value;
window.alert(a); // displays Left or Right button value
}
</script>
i tried inputClick(Left); and inputClick(Roght); but do nothing :(
What i need is when page load ::
rnd = random(2);
switch(rnd)
case 1:
inputClick(Left);
case 2:
inputClick(Right);
i DONT want button or eventlistener
I hope this helps. http://jsfiddle.net/Rh7Ju/1/
Know that anything in the YUI().use() will execute when the DOM is ready.
YUI().use('node', 'event', function (Y) {
function inputClick(button_value) {
alert(button_value);
}
// called when the buttons are clicked
Y.one('#btns').on('click', function (e) {
inputClick(e.target.get('value'));
}, 'input');
inputClick('Right'); // called when the dom is ready.
});
After I looked at your question again, is seems like you are trying to randomly select a button and alert its value. So, maybe this is more what you're looking for?
http://jsfiddle.net/Rh7Ju/2/
Anyway, happy coding.

addEventListener to div element

I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.

how can I intercept a click for all img's ? I have a bunch of images, each needs to reply to a click.

I would like to present images to my users, where they can select them. I need them to select a limited number, say 5, so:
The images are shown in a matrix, and the user can click them.
I thought:
function boom()
{
this.css('background-color','#fff');
this.data('clicked','yes');
// I should also make checks here to see how many were clicked already
}
$('img').click(boom);
// I thought this would connect all img's that were clicked upon to this function, where I can call the 'this' with the css function...
But it doesn't work as I thought it would...
Any help would do, thanks !
$(function(){
var clicked_img = 0;
$('img').click(function(){
$(this).css('background-color','#fff').data('clicked','yes');
clicked_img++;
});
});
EDIT: UPDATED CODE BELOW FOR NEW REQUEST, FOUND IN COMMENT THREAD:
Per your updated code request, if your HTML is this:
<img id="one" class="clicked" src="img/one.png" />
<img id="two" class="clicked" src="img/two.png" />
This JQuery has been fixed to work for you:
$('img.clicked').click(function(){
boom(this);
});
function boom(e) {
if($(e).data('clicked')=='yes') {
$(e).data('clicked','no').css('border','none');
}
else {
$(e).data('clicked','yes').css('border','3px solid #cccccc');
}
}
Working demo of the new code: http://jsfiddle.net/Vwye8/
Try assigning a variable to an annonymous function
var boom = function()
{
this.css('background-color','#fff');
this.data('clicked','yes');
// I should also make checks here to see how many were clicked already
}
and then calling the $('img').live("click",boom);
js fiddle here: http://jsfiddle.net/t7u6t/

Categories