Return var in a Jquery function [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 want return the var "Page" in a Jquery function :
var Page ;
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
return Page = 'Crea_Bouton';
});
alert(Page); //does not work
But its does not work.
The goal is not to make an alert of the var Page.
In a other page i have : if(Page == 'Crea_Bouton') { //Action }
So, Page must be a global var
Can you help me, please?

There's several issues here. First of all, Page and page are two different variables, but let's assume you've named them the same - your code still won't work.
The problem is, your event handler is not run immediately, it's only run when the double click occurs. Defining page outside of the event doesn't make any sense in this context. What happens is it hits var page; first, then it registers an event (but DOES NOT run the event function), then alerts an empty variable (because the event has not been triggered yet).
When you do trigger the dblclick event, that alert doesn't get executed.
Try this:
var page;
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
page = 'Crea_Bouton';
});
$('#anotherdiv').click(function(){
if(page === 'Crea_Bouton'){
alert("yep!");
}else{
alert("Something else")
}
})
Now, when your #anotherdiv is clicked, it will only alert 'yep!' if the original Montant div has been double clicked first. Otherwise it'll do something else (or nothing at all if you omit the else).
Here's an example jsfiddle:
http://jsfiddle.net/Wb9Ba/
If you click the second button right away, it says "Something else", but if you double click the first button, and then click the second button, it says "yep!"

Use a "callback" function as jQuery does:
function onReturn(page) {
// Process your returned value
if (page == 'Crea_Bouton') {
// Action
alert(page);
}
}
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
var page = 'Crea_Bouton';
onReturn(page);
});
Or process your value inside the dblclick callback:
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
var page = 'Crea_Bouton';
// Do something with my page
if (page == 'Crea_Bouton') {
// Action
alert(page);
}
});

Since the anonymous method inside dblclick is asynchronous, it's impossible to return something.
Instead, you may create a new function:
var page;
$('#Montant').dblclick(function () {
$("#Encadrement_Encaissement_Menu_Creation").show();
display('Crea_Bouton');
});
function display(page) {
alert(page);
// ...
}

Related

Have javascript prompt only display after page is loaded [duplicate]

This question already has answers here:
window.onload vs $(document).ready()
(17 answers)
Closed 6 years ago.
we are building off a battleship game in github.
Battleship
Here user, is prompted with his name and position of his ships and based on the answer, output is displayed on a textarea called domsole.
Domsole = (function($) {
var output;
var init = function(outname) {
output = $('#'+outname);
output.attr('disabled', 'disabled');
};
var ask = function(question) {
write(question);
var text = prompt(question);
write('> ' + text);
return text;
};
var write = function(text) {
output.append(text + "\n");
output.scrollTop(9999999999);
};
return {
ask: ask,
init: init,
write: write
};
})(jQuery);
$(document).ready(function() {
Domsole.init('domsole_out');
});
However, the all the prompts are asked before the page is loaded.
some of the prompts are
this.name = Domsole.ask("What's your name, Playa?");
Domsole.write("Alright, " + this.name + " you shall be.");
........
......
var coord = Domsole.ask("Where would you like to take a shot? Valid input is: x, y");
These code that calls Domsole.write and Domsole.ask are also in document.ready.
Here all the prompts are asked before anything is displayed on the screen? How to resolve this issue?
It's a good habit to put your JS script tags at the end of the body, so that all your HTML loads first.
The browser engine loads HTML and JS in the order they appear in the document, but it's better to take ownership of that load order. One possible event order is:
domsole.js loaded.
battleship.js loaded.
index.html document ready event.
Game starts here.
No JS code should have executed before that last step. So make sure that your prompts are not called prior to that point.
It seems that you don't understand the execution flow of your application. There is no possible way that these questions are displayed before the page is loaded unless you have another call to the init function that you have not mentioned. The output variable will be undefined until the init method is called and would therefore lead to javascript errors if ask was called before init is called. It seems that you are mistaking "loading" for "rendering". If you want to ensure that rendering of the page has been completed before your code is executed than you should use a timeout of around 50ms to call your initialization functions. Any modifications to the page triggered in jquery's ready event will not be displayed until after the event processing is completed. By calling the setTimeout function within the ready event handler you can delay processing until after the rendering of ready event handlers are completed.

Add function call as parameter to onclick function onclick="foobar(cb_func)" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using onclick for an element, but need to pass a callback to it like this:
function cb_func() {
alert("hello world!");
}
function foobar(i, cb) {
do something
if (cb != undefined)
cb();
}
onclick="javascript:foobar(1, cb_func)"
foobar gets called, but my cb_func isn't - in fact when I step in to cb() usinf Firebug, it shows me the HTML for the entire page.
Any ideas how I might achieve this?
Use event delegation:
$(document).on('click', '.dynamicGeneratedEl', function(event){
// do something
cb_func();
});
Where .dynamicGeneratedEl is a suitable selector for your case.
comment the line // do something
function cb_func() {
alert("hello world!");
}
function foobar(i, cb) {
// do something
if (cb != undefined)
cb();
}
Try this:
https://jsfiddle.net/h3ckcgvv/2/
var nextFunction = function() {
// some more stuff happens
}
var processClick = function() {
// some stuff happens
// condition
nextFunction();
}
$('.js-click-me').click(processClick);
The condition could be anything, based on page inspection, javascript variable state, data attributes on the clicked HTML element etc. Much more stable and maintainable than onclick attributes and hardcoding the callback into every call where it's needed.

Understanding flow in javascript [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
very new to JS and just playing around with examples I have written from a book.
With the code below - why are my functions not being executed? I am calling them and the syntax is correct. If I place document.addEventListener ("DOMContentLoaded" , init , false) ;
then the init() function will execute but not the test() function.
I am also confused as to where the document.addEventListener should be placed normally and exactly what it means with regards to the init function. Should the init() function always be called first? What normally goes in an init()function?
Thanks in advance. Code below ;
function init() {
var panel = document.getElementById("panel");
panel.innerHTML = "Hello World";
}
function test() {
var panel = document.getElementById("panel");
panel.innerHTML = "See ya";
}
init();
test();
You are probably executing the functions before the DOM elements have been loaded. The page is read from top to bottom. If the function executes before the HTML is read, the element won't exist.
Many developers make the script the last element in the body to avoid this.
Or use an onload handler, like this
window.onload = function () {
init();
test();
}
The functions do not need to be defined in the handler
EDIT. It is also true that you are writing data to the same element, so only the second function will have a result you can see. You can write to a separate element, or do as one answer suggests and add the data together.
It sounds like the methods are being called, but they are raising errors because they are called before the DOM is finished loading. Under normal circumstances, script like this will be executed as soon as the browser reaches it, so if this happens before the DOM is loaded (which is usually the case), the calls to document.getElementById() will fail because the document hasn't been loaded.
You're close with your call to document.addEventListener ("DOMContentLoaded" , init , false); - this tells the browser to call init when the DOM has been loaded. However, you're only calling init in this case, so test() doesn't get called.
I would suggest removing your inline calls to init(); and test();, then adding the following:
function onLoaded(){
init();
test();
}
and then calling onLoaded from your event listener:
document.addEventListener ("DOMContentLoaded" , onLoaded , false);

Return parent function from child function on click

How can I return a parent function from a child function on click? Here's an example code:
function returnFunction() {
var output = false;
$('a').click(function() {
output = true;
});
return output;
}
var result = returnFunction();
The result will always be false since the click hasn't happened at the time the code is being run. How could I make this work though?
My intention is to call pop-up dialogs, and I'd like to have all the logic inside one function that can easily be loaded - including the click events of a Confirm dialog box.
Elsewhere in scripts I'd be calling it this way for example:
// Menu click triggers the dialog
$('a').click(function(e) {
// The function displays the dialog and returns the click events of the dialog
var result = returnFunction();
// If result was false, we'll prevent the menu access, for example
if (!result) {
e.preventDefault();
}
});
I'm aware of the jQuery UI dialog plugin. But I'd like to achieve this without it for now.
Thanks.
An over-simplification of it is:
Everything stops (including scrolling and clicking on hyperlinks) while executing javascript. This means you cannot "pause" the script until someone clicks on a link.
The typical way of solving this is a callback function:
function my_callback(some, arguments) {
// you can do whatever in here: an ajax load, set a global variable, change some of the page, ...
console.log(some, arguments);
alert(some + " " + arguments);
}
function returnFunction(callback, param) {
var output = false;
$('a').click(function() {
callback(param, "world");
});
}
returnFunction(my_callback, "hello");
demo at http://jsfiddle.net/UnBj5/
EDIT:
I did mention global variables because they are an option, but they are typically bad style. Try to use other means if possible.
If you want more help with it, provide more details of what you are trying to do.
Try using parameters instead. Send a parameter to a function that shows your alert boxes, show a different pop-up alert depending on the parameter, what you are trying to do won't work because its basically a chicken-egg problem.

Conditional Statement Determined by Previous Page or Firing off a .click without clicking

I was wondering if this were possible.
I have a very complicated script, that runs on .click.
I want to run the same script without the user clicking as-well - in the instance that the user clicks to a new page with the correct content open - I have done this a thousand times but in this case the normal wont work..
so my question is, can you have a conditional statement that will do something (run a function) if the user has come from a specific page?
or
set off the .click function if in the query string say URL.client_id is present..?
You could do something like:
// evaluate id
if(URL.client_id) // or whatever you're passing through here
{
runFunction();
}
$('#element').click(function()
{
runFunction();
});
function runFunction()
{
console.log("runFunction called");
}

Categories

Resources