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);
Related
Looked for the answer all over, tried reading seperatly but couldn't find an answer..
I have a site, on which Google Tag Manager is implemented, and I need to extract the id of a clicked button (or its parent).
this is my code:
function(){
$(document).ready(function(){
var editid;
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
return editid;
});
}
Thanks!
The simplest approach is to create the following custom javascript variable:
function(){
return $({{Click Element}}).attr('data-id');
}
This will return the data-id attribute for all events (including clicks).
Attach this variable to the relevant event tag, and use click class contains uk-button as the trigger.
You can remove the outer function and code like below.
$(document).ready(function () {
$('div.uk-button').click(function () {
var editid;
editid = $(this).attr('data-id');
alert(editid);
});
});
Hey it looks like you may be not be catching the returned value of the document ready callback.
For example, this returns undefined since the return of $(document).ready() callback is not being returned by the containing function:
function testfunc() {
$(document).ready(function(){
var editid = 'this is the return value';
return editid;
});
}
testFunc()
"returns undefined"
I'm guessing that you might be trying to set up a custom javascript variable in GTM. You can still use document ready to ensure the elements are present but the returned value needs to be returned by the outer function for it to be passed into the variable.
So your example should work as follows:
function(){
var editid;
$(document).ready(function(){
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
});
return editid;
}
I want to get functions argument outside the scope, but have some kinds of problems to do that.
I have tried to get the value by this code: var text = $.commentString.text();
Live Demo
JQuery:
function addComment(commentString) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />', {
class: 'CommentStyle'
});
$('<label />', {
id: 'comment' + id,
text: commentString
}).appendTo(div);
var $edit = $('<p />', {
class: 'edit',
text: 'Edit'
}).addClass('edit').appendTo(div);
div.appendTo(container);
}
$('#divComments').on('click','.edit',function () {
var text = $.commentString.text();
});
In JavaScript it's not possible to get access to a variable outside of the scope which it was declared in. You could declare the variable outside of your function, but it will be overwritten every time the function runs - it doesn't look like this is the behaviour you're after.
What you can do in this example is use jQuery to traverse the DOM and find the text which you require.
$('#divComments').on('click','.edit',function () {
var text = $(this).parents(".CommentStyle").find("label").text();
});
then just declare a variable outside the function:
var someCommentString;
function addComment(commentString) {
someCommentString = commentString;
...
or u can try other way to get value but not sure its correct or not
$('#divComments').on('click','.edit',function () {
$(this).prev().text()
});
I've the following snip of a code:
var about = "about.html";
function loadPage(target){
$("#dashboard").load(target);
}
$(".nav li").click(function(){
loadPage($(this).attr("class"));
});
So when I click on a button like <li class="about">, target is = about.
But in that way, $("#dashboard").load(target); doesn't load the variable about which is the html-file which I want to load.
So how is it possible to call the variable in this way?
You seem to miss the .html part. Try with
$("#dashboard").load(target+'.html');
But, supposing you have only one class on your li element, you'd better use this.className rather than $(this).attr("class").
EDIT :
if you want to use your about variable, you may do this :
$("#dashboard").load(window[target]);
But it would thus be cleaner to have a map :
var pages = {
'about': 'about.html',
'home': 'welcome.jsp'
}
function loadPage(target){
$("#dashboard").load(pages[target]);
}
$(".nav li").click(function(){
loadPage(this.className);
});
A stupid answer : create a <a> tag, and set its href attribute to the correct value.
Otherwise :
A standard way to store key: values pairs in javascript is to use a plain object :
var urls = {};
urls['about'] = 'mysuperduperurlforabout.html';
function loadPage(target) {
var url = urls[target];
//maybe check if url is defined ?
$('#dashboard').load(url);
}
$(".nav li").click(function(){
loadPage($(this).attr("class") + ".html");
});
or
$("#dashboard").load(target+".html");
You can call the variables like this (if that's what you asked):
var test = 'we are here';
var x = 'test';
console.log(window[x]);
It's similar to the $$ in PHP. The output will be:
we are here in the console window.
You could put the "about" as an object or array reference similar to:
var pageReferences = [];
pageReferences["about"] = "about.html";
var otherReference = {
"about": "about.html"
};
function loadPage(target) {
alert(pageReferences[target]);
alert(otherReference[target]);
$("#dashboard").load(target);
}
$(".nav li").click(function () {
loadPage($(this).attr("class"));
});
Both of these alerts will alert "about.html" referencing the appropriate objects.
EDIT: IF you wished to populate the object based on markup you could do:
var otherReference = {};
$(document).ready(function () {
$('.nav').find('li').each(function () {
var me = $(this).attr('class');
otherReference[me] = me + ".html";
});
});
You could even store the extension in an additional attribute:
var otherReference = {};
$(document).ready(function () {
$('.nav').find('li').each(function () {
var me = $(this).attr('class');
otherReference[me] = me + "." + $(this).attr("extension");
});
});
Better would be to simply put the page reference in a data element:
<li class="myli" data-pagetoload="about.html">Howdy</li>
$(".nav li").click(function () {
loadPage($(this).data("pagetoload"));
});
Hi all thanks for taking a look.
I am trying to call a javascript function when I click on the update button.
Here is the javascript
var text2Array = function() {
// takes the value from the text area and loads it to the array variable.
alert("test");
}
and the html
<button id="update" onclick="text2Array()">Update</button>
if you would like to see all the code check out this jsfiddle
http://jsfiddle.net/runningman24/wAPNU/24/
I have tried to make the function global, no luck, I can get the alert to work from the html, but for some reason it won't call the function???
You have an error in the declaration of the pswdBld function in your JavaScript.
...
var pswdBld() = function() {
---^^---
...
This is causing a syntax error and avoiding the load of your JavaScript file.
See the corrected version.
Also, you may consider binding the event and not inlining it.
<button id="update">Update</button>
var on = function(e, types, fn) {
if (e.addEventListener) {
e.addEventListener(types, fn, false);
} else {
e.attachEvent('on' + types, fn);
}
};
on(document.getElementById("update"), "click", text2Array);
See it live.
In your fiddle, in the drop-down in the top left, change "onLoad" to "no wrap (head)"
Then change
var text2Array = function()
var pswdBld() = function()
to
function text2Array()
function pswdBld()
and it will alert as expected.
You have a syntax error in the line below..
var pswdBld() = function
^--- Remove this
supposed to be
var pswdBld = function
Also make sure you are calling this script just at the end of the body tag..
Because you are using Function Expressions and not Function Declaration
var pwsdBld = function() // Function Expression
function pwsdBld() // Function Declaration
Check Fiddle
I have a problem with my variable scope in a simple slider script that I´ve written (I don't want to use a readymade solution because of low-bandwidth). The slider script is called on statically loaded pages (http) as well as on content loaded through AJAX. On the statically loaded page (so no AJAX) the script seems to work perfect. However when called through AJAX the methods called can't find the elements of the DOM, which halts the necessay animation that is needed for the slider.
All the events are handled through even delegation (using jQuery's on() function), this however provided no solution. I'm quite sure it has something to do with the structure and variable scope of the script, but am unable to determine how to change the structure. So I'm looking for a solution that works in both situations (called normal or through AJAX).
I tried to declare the needed variables in every function, this however resulted in some akward bugs, like the multiplication of the intervals I set for the animation, because of the function scope. Hope somebody can help me in the right direction.
// Slider function
(function (window, undefined) {
var console = window.console || undefined, // Prevent a JSLint complaint
doc = window.document,
Slider = window.Slider = window.Slider || {},
$doc = $(doc),
sliderContainer = doc.getElementById('slider_container'),
$sliderContainer = $(sliderContainer),
$sliderContainerWidth = $sliderContainer.width(),
slider = doc.getElementById('slider'),
$slider = $(slider),
$sliderChildren = $slider.children(),
$slideCount = $sliderChildren.size(),
$sliderWidth = $sliderContainerWidth * $slideCount;
$sliderControl = $(doc.getElementById('slider_control')),
$prevButton = $(doc.getElementById('prev')),
$nextButton = $(doc.getElementById('next')),
speed = 2000,
interval,
intervalSpeed = 5000,
throttle = true,
throttleSpeed = 2000;
if (sliderContainer == null) return; // If slider is not found on page return
// Set widths according to the container and amount of children
Slider.setSliderWidth = function () {
$slider.width($sliderWidth);
$sliderChildren.width($sliderContainerWidth);
};
// Does the animation
Slider.move = function (dir) {
// Makes use of variables such as $sliderContainer, $sliderContainer width, etc.
};
// On ajax call
$doc.on('ajaxComplete', document, function () {
Slider.setSliderWidth();
});
// On doc ready
$(document).ready(function () {
Slider.setSliderWidth();
interval = window.setInterval('Slider.move("right")', intervalSpeed);
});
// Handler for previous button
$doc.on('click', '#prev', function (e) {
e.preventDefault();
Slider.move('left');
});
// Handler for next button
$doc.on('click', '#next', function (e) {
e.preventDefault();
Slider.move('right');
});
// Handler for clearing the interval on hover and showing next and pervious button
$doc.on('hover', '#slider_container', function (e) {
if (e.type === 'mouseenter') {
window.clearInterval(interval);
$sliderControl.children().fadeIn(400);
}
});
// Handler for resuming the interval and fading out the controls
$doc.on('hover', '#slider_control', function (e) {
if (e.type !== 'mouseenter') {
interval = window.setInterval('Slider.move("right")', intervalSpeed);
$sliderControl.children().fadeOut(400);
}
});
})(window);
The HTML example structure:
<div id="slider_control">
<a id="next" href="#next"></a>
<a id="prev" href="#prev"></a>
</div>
<div id="slider_container">
<ul id="slider">
<li style="background-color:#f00;">1</li>
<li style="background-color:#282">2</li>
<li style="background-color:#ff0">3</li>
</ul>
</div>
I notice you have
Slider.setSliderWidth = function() {
$slider.width($sliderWidth);
$sliderChildren.width($sliderContainerWidth);
};
which is called on ajax complete.
Does you ajax update the DOM giving a new DOM element that you could get to by doc.getElementById('slider')? Then your var slider and jquery var $slider are likely pointing to things that no longer exist (even if there is a dom element with slider as the id). To rectify, whenever the ajax is invoked that replaces that element, reinitialize slider and $slider to point to the new jquery wrapped element using the same initialization you have.
slider = doc.getElementById('slider');
$slider = $(slider);
Edit:
I'm not sure where you're going with the variable scope issue, but take a look at this example.
<pre>
<script>
(function(){
var a = "something";
function x (){
a += "else";
}
function y() {
a = "donut";
}
function print (){
document.write(a +"\n");
}
print ();
x();
print ();
y();
print ();
x();
print ();
})();
document.write(typeof(a) + "\n");
</script>
</pre>
It outputs into the pre tag
something
somethingelse
donut
donutelse
undefined
This isn't all that different from what you're already doing. As long as a is not a parameter of a method and is not declared with var in a nested scope, all references to a in code defined within your function(window,undefined){ ...} method will refer to that a, given that a is defined locally by var to that method. Make sense?
To begin, surely you can replace all the getElementById using a jQuery approach. i.e. replace $(doc.getElementById('next')) with $('#next')
I think that when you use on it doesn't search the element for the selector as you are assuming. So you would have to use:
$doc.on('click', '#slider_control #prev',function(e){
e.preventDefault();
Slider.move('left');
});
Wait, what gets loaded through Ajax? The slider-html code? In that case, the Slider has already been 'created' and a lot of your variables will point to nowhere (because these DOM elements did not existed when the variables were initialized). And they will never do so either.