Passing jquery variable to another function - javascript

Not sure why this isn't working, and it's returning as an object/undefined.
I have a variable outside above the doc.ready:
var video_box_original_link = '';
I have a link that I click on inside the ready function which grabs the info fine:
$(document).on('click', '.youtube_video', function(video_box_original_link){
var my_game_name = $('a.game_title_link').attr('name');
var my_game_platform = $('a.game_platform_link').attr('name');
video_box_original_link = "/"+my_game_platform+"/"+my_game_name+"/videos";
});
And I have a function that I'm trying to pass to this which is also in the doc.ready down below:
$(document).on('click', '.popblock_box', function(e, video_box_original_link){
window.history.pushState("vidPage", "vidPopped", ""+ video_box_original_link +"");
}
Is this should be fine?
The "e" is for something else in the script which is not necessary to show.

You couldn't pass variable to callback like you do like you do in function(video_box_original_link) you should define it in global scope then just use it :
var video_box_original_link = '';
$(document).on('click', '.youtube_video', function(){
var my_game_name = $('a.game_title_link').attr('name');
var my_game_platform = $('a.game_platform_link').attr('name');
video_box_original_link = "/"+my_game_platform+"/"+my_game_name+"/videos";
});
$(document).on('click', '.popblock_box', function(e){
window.history.pushState("vidPage", "vidPopped", ""+ video_box_original_link +"");
}
Hope this helps.

Related

How to append a href link with a select tag value

I am attempting to change a href link based on two different select tags changed
So far I have got it to append with 1 select tag, however i cannot get it to work with the other.
Any help or suggestions would be appreciated. Thanks
$('#to').on('change', function() {
var value2 = $(this).val();
});
var base_href="/converter/";
$('#from').on('change', function() {
var value=$(this).val();
if (base_href=="")
base_href = $("#cch-link").attr("href");
$("#cch-link").attr("href",base_href+value+'-to-'+value2);
});
You are defining the value2 variable in the context of the first handler, outside of that context the variable is undefined, you can define a global variable or:
var base_href = "/converter/";
function setHref()
{
$("#cch-link").attr('href', function()
{
var to = $('#to').val();
var from = $('#from').val();
return base_href + from + '-to-' + to;
});
}
$('#to, #from').on('change', setHref); // .change();

Keeping variables between function executions (Javascript)

I have a JavaScript function that runs every time one of the many links is clicked. The functions first checks what the id of the link clicked is, then it runs an if stement. depending on the id of the link, different variables are defined.
All this works, but the problem is that some links define one variable while other links define another, I need to keep the variables defined in previous executions of the function defined for other executions of the function.
An example follows:
$(document).ready(function()
{
$(".sidebar a").click(function(event) {
event.preventDefault()
var targetID = $(this).attr("data-target")
$("#" + targetID).attr("src", $(this).attr("href"))
var element = $(this).attr("class")
if (element == "submit") {
var submit = $(this).attr("user")
alert("1")
} else if (element == "view") {
var view = $(this).attr("user")
alert("2")
}
})
window.history.replaceState({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view)
})
Thanks
You can use an outer function which does nothing but declare some variables and return an inner function. The inner function can access the variables from the outer scope which stay the same for every call of the function.
Example
var next = (function() {
var value = 0;
function next() {
return value++;
}
}());
console.log(next());
console.log(next());
console.log(next());
Live demo
http://jsfiddle.net/bikeshedder/UZKtE/
Define the variables in an outer scope:
$(document).ready(function () {
var submit;
var view;
$(".sidebar a").click(function (event) {
event.preventDefault();
var targetID = $(this).attr("data-target");
$("#" + targetID).attr("src", $(this).attr("href"));
var element = $(this).attr("class")
if (element == 'submit') {
submit = $(this).attr("user")
alert("1")
} else if (element == 'view') {
view = $(this).attr("user")
alert("2")
}
});
});
Create var submit and view outside of the function so it has a global scope.
You can store arbitrary data on a matched element with JQuery's .data() function.
Example:
$(this).data("submit", $(this).attr("user")); // set a value
var submit = $(this).data("submit"); // retrieve a value
This places the data in the context of JQuery's knowledge of the element, so it can be shared between function calls and even between different events.

Jquery: How can I call back the same function with a different parameter after the 1st one has finished?

I've got a function that takes in a parameter to animate it.
I would like to call back this function with a different parameter in it after the previous one has finished. So far I have this, the animation works but it doesn't do it one after the other:
var thisis = document.getElementById("thisis");
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var txt3 = document.getElementById("txt3");
var txt4 = document.getElementById("txt4");
var txt5 = document.getElementById("txt5");
$("#thisis").fadeIn(400, function(){
animetxt(txt1, function() {
animetxt(txt2, function(){
animetxt(txt3, function(){
animetxt(txt4, function(){
animetxt(txt5);
});
});
});
});
});
function animetxt(o){ //.css and .animate on the parameter// }
Your help would be most appreciated :)
Your animetxt function does not have a parameter for the callback function that you are passing to it. Perhaps:
function animetxt(o, f) {
o.animate({/* css */}, f);
}

JavaScript: How stop a function which is started with $(function(){})

I created a function and then called this function when the page loads, also I need call same the function, but without it existing twice. I want it to just stop from $(function(){}) and call again when an element is clicked on.
function myfunction(){
console.log('message');
}
$(function(){
myFunction();
$('#id').click(function(){
...some code here ...
myFunction();
});
})
When page is loaded the console gives me: "message" - it's ok, but when click on #id then I get this message twice, if again then 3 times;
Here my code
function select_cta(){
$('.cta-id').click(function(){
console.log('-');
$('.cta-id').removeClass('active');
$(this).addClass('active');
var cta_arr = parseInt($(this).attr('id').replace('cta-button-', ''))-1;
$('.cta-image').fadeOut(300).removeClass('active');
$('#'+$(this).attr('id').replace('cta-button', 'cta-image')).fadeIn(300).addClass('active');
if(cta_data[cta_arr]){
$('.cta-actions #cta_id').val(cta_data[cta_arr].id);
}
else{
$('.cta-actions #cta_id').val('');
};
if(cta_data[cta_arr]){
$('.cta-actions #cta_link').val(cta_data[cta_arr].link);
}
else{
$('.cta-actions #cta_link').val('');
};
});
}
$(function(){
select_cta();
$('.add-new-cta').click(function(){
var new_tab = parseInt($(this).prev().attr('id').replace('cta-button-',''))+1;
$(this).before('<div id="cta-button-'+new_tab+'" class="cta-btn cta-id empty" style="display:none;"><span>'+new_tab+'</span><span class="onair">ON</span></div>');
$('#cta-button-'+new_tab).fadeIn(300);
$('.cta-images').append('<div id="cta-image-'+new_tab+'" class="cta-image " style="display:none"><img src="/assets/images/page/placeholder_cta.gif"></div>');
select_cta();
})
});
Your problem that every call to select_cta adds another handler to each of the elements. They all would be executed when the click event fires. Two solutions:
Unbind the event handlers from all elements before you re-add them. To do so, begin the function select_cta with $('.cta-id').off("click").on("click", function(){…
Better: use event delegation:
jQuery(function($){
function getIdNumber($el) {
return parseInt($el.prop('id').replace(/\D/g, ''), 10);
}
var $active = $('.cta-id.active'),
$activeImg = $('.cta-image.active')
$(document).on("click", '.cta-id', function(e) {
$active.removeClass('active');
$active = $(this).addClass('active');
var num = getIdNumber($active);
$activeImg.fadeOut(300).removeClass('active');
$activeImg = $('#cta-image'+num).fadeIn(300).addClass('active');
var cta_arr = num - 1;
if(cta_arr in cta_data) {
$('#cta_id').val(cta_data[cta_arr].id);
$('#cta_link').val(cta_data[cta_arr].link);
} else {
$('#cta_id').val('');
$('#cta_link').val('');
}
});
$('.add-new-cta').click(function(e) {
var $this = $(this),
new_tab = getIdNumber($this.prev())+1,
new_button = $('<div id="cta-button-'+new_tab+'" class="cta-btn cta-id empty" style="display:none;"><span>'+new_tab+'</span><span class="onair">ON</span></div>');
$this.before(new_button);
new_button.fadeIn(300);
$('.cta-images').append('<div id="cta-image-'+new_tab+'" class="cta-image " style="display:none"><img src="/assets/images/page/placeholder_cta.gif"></div>');
})
});

Pass parameters to function call in event trigger

Right now I have this
jQuery('.widget-prop').keyup(function() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();
stuff;
}
and
jQuery('.widget-prop').click(function() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();
stuff;
}
two functions are the same, so I'd like to simplify it by defining external function and calling it with
jQuery('.widget-prop').click('myFunction');
but how would I pass parameters to myFunction?
function myFunction(element) {
stuff;
}
Thanks
Get rid of those quotes...
jQuery('.widget-prop').click(myFunction);
Firstly you can combine both your handlers into one:
jQuery('.widget-prop').on('click keyup', function() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();
// stuff;
});
Or for older versions of jQuery:
jQuery('.widget-prop').bind('click keyup', function() { // ... });
Secondly, jQuery will automatically apply the current element to any function you provide, so the this keyword will still be the element raising the event when you do this:
jQuery('.widget-prop').on('click keyup', myHandler);
function myHandler() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();
// stuff;
}
Use the .on function instead of the shortcut .click and pass all required events as paramter:
jQuery('.widget-prop').on('click keyup', function() {
var prop = jQuery(this).attr('id');
var val = jQuery(this).val();
//stuff;
});
EDIT: deprecated => shortcut
In the context of MyFunction this is your clicked element. Additionally, the click handler takes 1 argument, so your function signature should be function MyFucntion(event) where the event argument holds data about the action (e.g. event.target is the clicked element).
so this is how you would define your handler:
function myFunction(event){
var element = event.target;
// Note: event.target == this
//do stuff
}
and this is how you would bind it to the event:
$(".widget-prop").click(myFunction);

Categories

Resources