views:

538

answers:

3

*I would like to use single a href link to call different functions .

On first click it should call first_function() and on second click it should call second_function.
Like toggling between two functions using same link. Suggest the best way to be done.*

Jquery Code :

$(function() {

 var IntervalId;

 function first_function() {
  //code goes here
 }; 

 function second_function(){  
  //code goes here
 }  

$("#link2").click((function(){
second_function();
}));

$("#link1").click((function(){
first_function();
}));

});

Html Code :

<a href="javascript:void(0);" id="link2">Call function2</a>
<a href="javascript:void(0);" id="link1">Call function1</a>
+3  A: 

"Like toggling between two functions using same link."

$("#link1").toggle(
 function first_function() {
  // Code goes here 
 },
 function second_function(){  
  // Code goes here 
 }  
);

From the jQuery docs on toggle(fn1, fn2, [fn3, [fn4, [...]]]):

Toggle among two or more function calls every other click.

Tomalak
forgot all about toggleing :)
balexandre
http://visualjquery.com/ is quite helpful in finding functions you never knew about.
Tomalak
Thanks Tomalak for the link . I have updated the question with more info . Check it out.
Webrsk
A: 

the easiest way would be

var performFirstAction = true;

$(function() {

 function first_function() {
  // Code goes here 
 } 

 function second_function(){  
  // Code goes here 
 }  

 $("#link1").click(function(){
  if(performFirstAction) {
    first_function(); performFirstAction = false; }
  else {
    second_function(); performFirstAction = true; }
 });
});

or using toggle as Tomalak mention and well,

$(function() {

 function first_function() {
  // Code goes here 
 } 

 function second_function(){  
  // Code goes here 
 }  

 $("#link1").toggle(
   first_function,
   second_function
 );
});
balexandre
A: 

Javascript:

$(document).ready(function() {
    function first_function() {
        // Code goes here 
    }; 

    function second_function(){  
        // Code goes here 
    }

    $("#link").toggle(first_function, second_function);
});

HTML:

<!-- I'm pretty sure that <a> isn't the right tag for this. -->
<button id="link">Toggle between the two functions.</button>
Georg
gs Can you explain why button is more right way than <a> tag ?
Webrsk
<a> is a link which is supposed to open another page instead of executing javascript. You can - of course - use any other element like <span> or <div>.
Georg