Newman
Newman

Reputation: 23

jquery and javascript if...else problem

I've been trying to figure this one out for some time now, but no luck.

I use simplest jquery and ajax to load content into my page when navigation bar or sidebar links are clicked. I simply put this in document.ready:

$("#nav ul li a").click(function(){content_load($(this).attr('href'));return false;}); 

My content_load function is this:

function content_load(toLoad)
  {
  $('#content').hide('fast',loadContent);  
  function loadContent() 
    {  
    $('#content').load(toLoad,'',function(){showNewContent();tb_init('a.thickbox, area.thickbox, input.thickbox');});  
    }  
    function showNewContent()
      {  
      $('#content').show('fast');
      }  
   }

This works!

But...when I put simple if...else statement in function_load(), instead of simple ajax load, I get navigated to the page I wanted to load with load() function. It's like "return false" is ignored...

So this is the code that "breaks" everything:

function content_load(toLoad)
  {
  if(toLoad=="content/page1.html") {//do something}
  else
    { 
    $('#content').hide('fast',loadContent);  
    function loadContent() 
      {  
      $('#content').load(toLoad,'',function(){showNewContent();tb_init('a.thickbox, area.thickbox, input.thickbox');});  
      }  
      function showNewContent()
        {  
        $('#content').show('fast');
        }  
     }
   }

Any idea why???

Thanks! Newman

Upvotes: 2

Views: 762

Answers (3)

Felix Kling
Felix Kling

Reputation: 817208

Maybe it is a weird scope problem. Put the functions outside the if...else statement, or even better, use anonymous functions:

function content_load(toLoad) {
   if(toLoad=="content/page1.html") {
      //do something
   }
   else { 
      $('#content').hide('fast', function() {
         $(this).load(toLoad, function() {
             $(this).show('fast');
             tb_init('a.thickbox, area.thickbox, input.thickbox');
         });
      });
   }
}

That you are redirected to the page means that your function errors somewhere. If you have code where you have //do something, you should examine it too.

The error console of your browser should give you at least some information.


Instead of return false you can also call the appropriate methods of the event object:

$("#nav ul li a").click(function(event){
    // event.preventDefault();  <-- put here to always prevent reload, 
    //                              even on error (but should be avoided)
    content_load(this.href);
    event.preventDefault();
});

Upvotes: 2

sushil bharwani
sushil bharwani

Reputation: 30207

is it that your comment in first line commenting out the closing brace of your if statement

Upvotes: 2

The_Butcher
The_Butcher

Reputation: 2488

Don't know if that's a typo but the closing parentheses is commented out.

//do something}

That will cause it to break

Upvotes: 1

Related Questions