Accessing javascript array from onclick function - javascript

I am using jQuery and populating an array on document.ready.
In my page I have some elements with a click event. I defined that function outside of the document.ready function.
I can't seem to figure out how to access that array variable from within my onclick function.
To simplify, I would like something like this to work:
$(document).ready(function(){
var artists = new Array();
artists.push('item1');
artists.push('item2');
});
function clickLink() {
alert(artists[0]);
}

Many ways, one of the easiest, move your click hander inside the .ready() function. And you need to bind it to the element there instead of inline attribute:
$(document).ready(function(){
var artists = new Array();
artists.push('item1');
artists.push('item2');
$('#idOfTheElement').click(function() {
alert(artists[0]);
});
});

hi you lost scope of creation of array, so there is two ways to solve it
Put all in same scope:
$(document).ready(function(){
var artists = new Array();
artists.push('item1');
artists.push('item2');
function clickLink() {
alert(artists[0]);
}
});
Declare array as global:
var artists = new Array();
$(document).ready(function(){
artists.push('item1');
artists.push('item2');
});
function clickLink() {
alert(artists[0]);
}

You have to declare the artists array outside the document.ready() function and bind the function with the click event.
var artists = new Array();
$(document).ready(function() {
artists.push('item1');
artists.push('item2');
});
$('button').click(function() {
console.log(artists[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click</button>

A simple solution is to remove the var keyword when you declare the array variable, which will make the variable global and that is not recommended and another solution would be to declare your array outside the function so that it can be referenced from onclick function.

Related

Google Tag Manager - storing id of a clicked div/button

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;
}

jQuery order for 2 methods to be executed when document ready

I have this situation.
$(document).ready(function(){
$.each(elements,do());
});
I would like to execute another new method after the $.each() has finished new method called doOther().
Where I can set my new method for example doOther(); ? I have new $.each inside new method just for info.
Update
This is my script
$(function(){
$.each($('.countdown'), function() {
var _element = '.countdown-'+$(this).attr("id");
if ($(_element).length > 0) {
var _expDate = $(_element).attr('data-expiration').split(',');
_expDate.forEach(function(v,i,a){a[i]=parseInt(a[i]);});
var _datetime = new Date(_expDate[0],_expDate[1],_expDate[2],_expDate[3],_expDate[4],_expDate[5]);
init_countdown(_element,_datetime);
}
});
$.each($('.countdown'),function() {
var ips = $(this).text().split(',');
$(this).html('<div class="span12">'+ips[0]+'</div>');
});
});
function init_countdown(_element,_datetime){
$(_element).countdown({
date: _datetime /*"June 7, 2087 15:03:26"*/
});
}
it seems that $.each($('.countdown') etc.. is overridden by the first $.each, can't understand why.
If I've understood what you mean, your code should look like this:
$(document).ready(function(){
$.each(elements, do);
doOther();
});
If this isn't what you meant, please edit your original question and add more detail.
This should do it,
$(document).ready( function(){
$.each(elements,do());
doOther();
} );
Implement another method right after your first $.each block

$(this).html not working in jquery

<globemedia id="1"></globemedia>
<script type="text/javascript">
$("globemedia").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
$.get("getmedia.jsp?mediaID="+globeIDxMedia,function(a){
$(this).html(a);
});
});
</script>
The above Script i use to load content to my customized tag say <getmedia id="1"></getmedia>
script works fine till getting data from the page getmedia.jsp but when i use $(this).html(a); its not loading the data.
Got Answer from jquery forum
It'll work with custom tag as well
<script type="text/javascript">
$(document).ready(function(){
$("div[data-globalmedia]").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
$(this).load("getmedia.jsp?mediaID="+globeIDxMedia);
});
});
</script>
jQuery expert gave me solution you have to use $(document).ready(function(){}); and it works like a charm
Keep a reference to $(this) outside the $.get() function.
<script type="text/javascript">
$("globemedia").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
var self = $(this);
$.get("getmedia.jsp?mediaID="+globeIDxMedia,function(a){
$(self).html(a);
});
});
</script>
The meaning of this is different within the callback of $.get than it is within the callback of the outer $().each. You can read more about the semantics of this here: http://www.sitepoint.com/javascript-this-gotchas/
As a rule, if you want to refer to the "outer" value of this within a callback function, you first have to bind it to a variable that is accessible within the callback (in this case, I've used the common convention of a variable named self).
You can't this ( which refers to globemedia ) within $.get() callback function scope. Within $.get() callback function this refers to something else but not globemedia.
So, get keep reference of this outside of $.get() which refers to globalmedia like following:
$("globemedia").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
// keep referece to this
// ie. globemedia
var media = $(this);
$.get("getmedia.jsp?mediaID="+globeIDxMedia,function(a){
// here self refers to
// globemedia element
media.html(a);
});
});
Note
I think $("globemedia") should be $(".globemedia"). That means you should use a class selector.
You can't make your own custom HTML tag. See HERE
As you can't create you own HTML tag (here, globalmedia), instead of that you can use data attribute to them. For example:
<div data-globalmedia="media1" id="id_1">Media 1</div>
<div data-globalmedia="media2" id="id_2">Media 2</div>
and so on. And for jQuery you can use:
$('[data-globalmedia]').each(function() {
var globeIDxMedia = $(this).attr("id");
// keep referece to this
// ie. globemedia
var self = $(this);
$.get("getmedia.jsp?mediaID=" + globeIDxMedia, function(a) {
// here self refers to
// globemedia element
self.html(a);
});
});
Working sample

using jquery when passing arguments to function

I have a link which triggers js function. To the link I have attached data-attribute on html which I want to pass to the function.
$(".trigger").awesomeFunction({
oneArgument: "secretSauce",
secondArgument: $(this).data("address")
});
Now that second argument ends up null instead of the data-address attribute. Is it because $(this) is not in right scope inside the function arguments list and if so how could I refer to the originating link?
Not sure how your awesomeFunction is defined, but this seems to do the trick.
$.fn.awesomeFunction = function(obj){
console.log(obj.sauceType, this.data(obj.dataArg))
// returns 'secretSauce 123 Anystreet Dr.'
}
var div = $('#theDiv')
div.awesomeFunction({
sauceType : 'secretSauce',
dataArg : 'address'
})
JSFiddle
$(".trigger").each(function() {
var self = $(this);
self.awesomeFunction({
oneArgument: "secretSauce",
secondArgument: self.data("address")
});
});
Given your code sample, anything could happen, this is not defined in the scope of .trigger, you're "one layer out" so to speak.
See this fiddle for example
$(".trigger").click(function() {
var self = $(this);
self.awesomeFunction({
oneArgument: "secretSauce",
secondArgument: self.data("address")
});
});

Create JavaScript array of function pointer, without calling it

I have the code below. I would like to have an array (buttons) with a single element pointing to the a function (closeFlag).
<script type="text/javascript">
var closeFlag = new function() {
alert('Clicked');
}
var buttons = {
'OK': closeFlag
}
</script>
However, when loading the page the alert immediately pops up. When the array is constructed, instead of using it as a pointer, JavaScript calls my function.
Why? What mistake, misconception do I have?
The new keyword, you will not need it.
<script type="text/javascript">
var closeFlag = function() {
alert('Clicked');
}
var buttons = {
'OK': closeFlag
}
</script>
What's happening in your code is that it's constructing the anonymous function then assigning the result of it (this) to closeFlag.

Categories