Passing a variable from one function to another in JQuery? - javascript

I have 2 functions and i was wondering if it is possible to use a variable that is defined in 1 function, in another function. Basically I have the following code:
(function( $ ) {
//On input
$("#anid").on("input", function() {
var variable = 'testing';
});
//On change
$('#dropdown').change(function(){
var variable2 = variable;
});
})( jQuery );
Any help is greatly appreciated!

Just declare the var variable out of that context.
var variable = 'initialValue';
(function( $ ) {
//On input
$("#anid").on("input", function() {
variable = 'new Value'
});
//On change
$('#dropdown').change(function(){
//don't even need another one here..
//variable is accessible from here
});
})( jQuery );

I'll delete this once you comment and say to do so as the answer above is fine. If you do not need variable elsewhere, then it will be cleaner to do:
(function( $ ) {
var variable = 'initialValue';
//On input
$("#anid").on("input", function() {
variable = 'new Value'
});
//On change
$('#dropdown').change(function(){
//don't even need another one here..
//variable is accessible from here
});
})( jQuery );

Related

JavaScript ignores bool

i try to do something like a status-check to enable/ disable settings.
// file 1
function settings( valStatus ){
var status = valStatus;
this.getStatus = function(){
return status;
}
this.setStatus = function( valStatus ){
status = valStatus;
}
}
calling this function here:
// file 2
$settings = new settings( false );
$(document).ready(function() {
$( '#openSettings' ).on('click', function() {
$settings.setStatus( true );
enableSettings();
});
$('#save').on('click', function(){
$settings.setStatus( false );
closeSettings();
});
});
// file 1
enableSettings = function() {
if( $settings.getStatus() === true ){
//toggle emptyLink
$('.myButton').on('click', function(){
alert($settings.getStatus());
});
}
}
So as startup while clicking on "myButton" nothing happens.
After Clicking on "openSettings" and then on "myButton" i get the alert "true";
After clicking on "save" and then on "myButton" again, i get the alert "false", but it does not even trigger, because i checked it befere.... can somebody help me please?
Where is my mistake?
I think you probably want to put the check for status inside the .myButton click handler instead of outside. That way you only need to apply the handler once and it will either work or not depending on the value of status.
$(document).ready(function() {
var $settings = new settings( false ); // keep out of global scope
$( '#openSettings' ).on('click', function() {
$settings.setStatus( true );
});
$('#save').on('click', function(){
$settings.setStatus( false );
});
$('.myButton').on('click', function(){
if ($settings.getStatus()) {
alert($settings.getStatus());
}
});
});
First of all, you can write JavaScript with less code than e.g. Java. You don't need the getter and setter methods since there is no package visibility. Since you do nothing with the setters you can access your fields directly. This is less code to read and less code where you can have errors. So get rid of useless code (remember this is not the request do code one-liners). Search the internet for "clean code".
Since you are in JavaScript you can do better than that. A smaller approach to store your information.
var mySetting = {};
mySetting.status = true
console.log( mySetting.status );
mySetting.status = false;
console.log( mySetting.status );
Remember to keep your global space clean! Search the internet for "javascript global scope pollution". So do this within your scope.
Your main problem is, that you are using closures. You probably don't want to use it in your case. Search the internet for "javascript closure tutorial". There are a lot of good ones out there.
Since you are using the Jquery, you can use the .data() function to store your information.
See http://api.jquery.com/jquery.data/
$(function(){
$( '#openSettings' ).on('click', function() {
$('#settings').data( "status", true );
enableSettings();
});
$('#save').on('click', function(){
$('#settings').data( "status", false );
closeSettings();
});
$('.myButton').on('click', function(){
alert($('#settings').data());
});
});
Or within the HTML itself. See http://api.jquery.com/attr/
$('#settings').attr( "status", true );
console.log( $('#settings').attr( "status" ) );
Or as switches.
$('#settings').addClass( "settingsEnabled" );
$('#settings').removeClass( "settingsEnabled" );
console.log($('#settings').hasClass('settingsEnabled'));
Use .data() if you want to store object references and HTML for simple information like switches etc. The benefit is, that you can reach that information even with CSS.
And please get rid of the $ prefix in your own code since it has no meaning. If you use frameworks like angular it will help you to identify the origin or like the $$ the ("don't") use of it.

Javascript/jQuery set global variable of an unknown element

EDIT
TO BE DELETED. Issue was not code based but the global variable help was greatly appreciated and I did learn a lot.
How would you set a Global variable of an unknown element.
I need to pass a variable when an element is clicked to the rest of the functions in my code. I know I am somewhat close. I just need a bit of help.
My code is below. I am trying to pass my 'sampleName' and 'samplePath' to the 'loadPage' function only when an element is clicked.
(function ($) {
//Original Variables
//var sampleName = 'Book1'
// samplePath = '/Book1/'
//Want dynamic variables
var sampleName;
var samplePath;
$(document).on("click", ".sampleDiv", function (event) {
sampleName = $(this).attr("sample") || '';
samplePath = 'Books/' + sampleName;
//alert(sampleName);
// alert(samplePath);
});//End click
function loadPage(page) {
var img = $('<img />');
img.load(function () {
var container = $('.Book .p' + page);
img.css({ width: '100%', height: '100%' });
img.appendTo($('.Book .p' + page));
container.find('.loader').remove();
});
img.attr('src', samplePath + 'pages/' + page + '.jpg');
}
})(jQuery);
Thanks in advance.
/EDIT/
Hmmm. I must be asking this the wrong way.
More explanation.
Originally my code had 2 variable set statically.
Example:
var sampleName = 'Book1',
samplePath = '/Book1/'
What I am trying to do is make those variables more dynamic and set them when the
<div sample='Book1'></div>
is clicked on the variables (mainly the 'Book1' part) changes. Each 'Book' will have a different number (Book1, Book2, Book3, etc). I want to make the variables get set depending on which one gets clicked on. The attr("sample") on my DIV will determine the Book number. So when the DIV is clicked on the attr("sample") will be the variable's value.
Hope this helps with my issue in explaining more.
Just put all your global variables outside of your function.
var sampleName;
var samplePath;
(function ($) {
$(document).on("click", ".sample", function (event) {
sampleName = $(this).attr("sample") || '';
samplePath = 'Books/' + sampleName;
//alert(sampleName);
// alert(samplePath);
});//End click
If the variable is GLOBAL, it must be declared OUTSIDE the (function ($) {
.. ex:
var sampleName;
var samplePath;
(function ($) {
...
})(jQuery);

Calling a function inside a jQuery plugin from outside

I am trying to work out how to call functions within my jQuery plugin from outside the plugin. The code I have tried is not working. I'm sure I will have to restructure my plugin to allow this, but I'm not sure how to. In this example, I'm trying to access the underline() function.
jsFiddle
jQuery plugin
(function($) {
"use strict";
$.fn.testPlugin = function(options) {
// Settings
var settings = $.extend({
newText : "Yabadabado"
}, options);
return this.each(function(i, el) {
var init = function(callback) {
if( $(el).attr("class") === "red" ) {
$(el).css("color","red");
}
$(el).text(settings.newText);
if( callback && typeof(callback) === "function" ) {
callback();
}
};
var underline = function() {
$(el).addClass("underline");
};
init();
});
};
}(jQuery));
Assign the plugin to selectors
var doTest = $("#testItem").testPlugin({
newText: "Scoobydoo"
});
var doNewTest = $("#newTestItem").testPlugin({
newText: "kapow!"
});
Call a function that is located within the plugin
$("#underline").click(function(e) {
e.preventDefault();
doTest.underline();
});
Take a look at closures.
Here is a basic example of what a closure looks like in a jQuery plugin.
$.fn.plugin = function() {
return {
helloWorld: function() {
console.log('Hello World!');
}
}
};
// init plugin.
var test = $('node').plugin();
// call a method from within the plugin outside of the plugin.
test.helloWorld();
You can see another example at the following jsfiddle.
http://jsfiddle.net/denniswaltermartinez/DwEFz/
First thing first we need to understand each step in building a jQuery plugin, its like build a javascript plugin (class) but we have in addition to it a jQuery class.
//We start with a function and pass a jQuery class to it as a
//parameter $ to avoid the conflict with other javascript
//plugins that uses '$ as a name
(function($){
//We now append our function to the jQuery namespace,
//with an option parameter
$.fn.myplugin = function(options) {
//the settings parameter will be our private parameter to our function
//'myplugin', using jQuery.extend append 'options' to our settings
var settings = jQuery.extend({
param:'value',
}, options);
//Define a reference to our function myplugin which it's
//part of jQuery namespace functions, so we can use later
//within inside functions
var $jquery=this;
//Define an output object that will work as a reference
//for our function
var output={
//Setup our plugin functions as an object elements
'function1':function(param){
//Call jQuery reference that goes through jQuery selector
$jquery.each(function(){
//Define a reference of each element of jQuery
//selector elements
var _this=this;
});
//This steps is required if you want to call nested
//functions like jQuery.
return output;
},
//If we want to make our plugin to do a specific operations
//when called, we define a function for that
'init':function(){
$jquery.each(function(){
var _this=this;
//Note that _this param linked to each jQuery
//functions not element, thus wont behave like
//jQuery function.
//And for that we set a parameter to reference the
//jQuery element
_this.$this=$(this);
//We can define a private function for 'init'
//function
var privatefun=function(){}
privatefun();
//We can now do jQuery stuffs on each element
_this.$this.on('click',function(){
//jQuery related stuffs
});
});
//We can call whatever function we want or parameter
//that belongs to our plugin
output.function1("value");
}
};
//Our output is ready, if we want our plugin to execute a
//function whenever it called we do it now
output.init();
//And the final critical step, return our object output to
//the plugin
return output;
};
//Pass the jQuery class so we can use it inside our plugin 'class'
})(jQuery);
Using our function now is very easy
<div class="plugintest">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
<script>
$(function(){
var myplugin=$(".plugintest > span").myplugin({
param:'somevalue'
});
myplugin.function1(1).function1(2).function1(3);
});
</script>
In short, jQuery plugins and any Javascript plugins are simply about parameters scope.
Fiddle version
https://jsfiddle.net/eiadsamman/a59uwmga/

Store jQuery to a variable

I'm using Leaflet to make a map with a layer selector, and jQuery to bind to the radios made by the Leaflet layer selector. I'm able to view which radio was selected in an alert using the following code
$("[name='leaflet-base-layers']").change( function () {
alert('Layers selected: ' + $(this).parent().text());
});
I'd like to know how to store that data as a Javascript variable to be compared to in
if (ExampleVariable == "Phoenix") {
map.panTo([33.4314,-112.0747]);
}
Is there any way to do this, and if not, how can I use jQuery's internal data storage to do this?
Did you mean something like this?
var lastSelected = null; // if you need it later for anything
$("[name='leaflet-base-layers']").change(function(){
var text = $(this).parent().text();
lastSelected = text;
// use the text for anything
switch(text) {
case "Phoenix":
map.panTo([33.4314,-112.0747]);
break;
case "SomethingOther":
map.panTo([10, 120]);
break;
}
});
$("[name='leaflet-base-layers']").change( function () {
alert('Layers selected: ' + $(this).parent().text());
ExampleVariable = $(this).parent().text();
});
You could either save the value to a variable declared globally
var selLayer; // global
$( "[name='leaflet-base-layers']" ).change(function () {
selLayer = $( this ).parent().text();
});
Or, using jQuery data stores as
$( "[name='leaflet-base-layers']" ).change(function () {
$( this ).data( "selLayer", $( this ).parent().text());
});
if ($( "[name='leaflet-base-layers']" ).data( "selLayer" ) === "Phoenix") {
map.panTo( [33.4314,-112.0747] );
}
You should ideally store leaflet layer element to avoid jQuery lookup again and again.
var $leafletBase = $( "[name='leaflet-base-layers']" );
The simplest way is like this:
$("[name='leaflet-base-layers']").change(function() {
leafletText = $(this).parent().text());
});
Note that if you use the var keyword in that assignment, you're going to have scoping problems with your later comparison since that variable won't be accessible outside of that particular function. By omitting the var keyword, you're putting the var in the global context, which is something you should generally avoid when possible.
I would highly suggest learning about variable scoping as it's an important concept to grasp.

I can't access array/obj outside jQuery event function

So I've got an object, or array, declared at the beginning of anything, outside everything:
var Thing = {title:'horse'};
Then I've got:-
$('.clickedIt').fadeOut(200, function() { console.log(Thing.title); }
That will fail. However, if I place above that same console log out of fadeOut, it'll be fine.
If you want something to be global, just define it on the window Object.
window.Thing = { title: 'horse '};
Then use it like so:
$( '.clickedIt' ).fadeOut(200, function() {
console.log( window.Thing.title );
});
Just a note, putting a number of variables on the window Object is not recommended, I would recommend looking into name-spacing: http://addyosmani.com/blog/essential-js-namespacing/
Here is an example:
//simple JavaScript module
( function( window ) {
//define your applications root namespace
window.myApp = {
Thing: { title: 'horse '}
};
})( window );
//jQuery ready function
$( function() {
$( '.clickedIt' ).fadeOut( 200, function() {
console.log( myApp.Thing.title );
});
});
The value you assigned to title horse is undefined wrap it within quotes to make it string litral,
Live Demo
var Thing = {title:'horse'};
$('.clickedIt').fadeOut(200, function() { console.log(Thing.title); })​

Categories