Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  121] [ 6]  / answers: 1 / hits: 24136  / 12 Years ago, wed, march 21, 2012, 12:00:00

I have this:



$('#slider li').click(function () {
var stepClicked = $(this).index();
alert(stepClicked);
if (stepClicked != 0) {
$('#cs_previous').removeClass('cs_hideMe');
} else {
$('#cs_previous').addClass('cs_hideMe');
}

$('li.cs_current').removeClass('cs_current');
$($(this)).addClass('cs_current');


moveToNextImage(stepClicked);

function moveToNextImage(stepClicked) {
alert(stepClicked);
var currentIs = $('li.cs_current').index();
var newLeftEdge = currentIs - stepClicked;
$('.cs_riskStageImage').fadeTo(200, .2).animate({
left: newLeftEdge
}, fast).fadeTo(200, 1);
};
});


the alert shows the proper index for the li clicked, and when I alert the variable within the last function I'm calling, moveToNextImage(stepClicked), the same value shows but the animation isn't happening. This works many other ways, but I'm trying to pass the index value of the list item clicked to use for the math to calculate.



..or can I convert the value to another variable in the first function that I can pass to the second?


More From » jquery

 Answers
14

The javascript functions call() and apply() are both for precisely for the purpose of calling a function within a context.



function sum() { 
return this.num1 + this.num2;
}

function callSum(num1, num2) {
this.num1 = num1
this.num2 = num2
return sum.call(this); //call sum() in the context of this
}

alert(callSum(10, 15));

function applySum(num1, num2) {
this.num1 = num1
this.num2 = num2
return sum.apply(this); //call sum() in the context of this
}

alert(applySum(30, 45));


jsfiddle example link



Now in the sum() function the this keyword had the same context as it does in the callSum() and applySum() functions.



The difference between call() and apply() is that apply's second parameter is either an array of parameters to pass or an arguments object.


[#86688] Tuesday, March 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradenc

Total Points: 75
Total Questions: 96
Total Answers: 129

Location: Burundi
Member since Thu, Feb 10, 2022
2 Years ago
bradenc questions
Thu, Sep 2, 21, 00:00, 3 Years ago
Wed, Sep 1, 21, 00:00, 3 Years ago
Wed, May 6, 20, 00:00, 4 Years ago
Tue, Oct 8, 19, 00:00, 5 Years ago
;