Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

A while ago I used this code to load content into a div using jQuery load. I repeated the code for all the clicks to load different pages in the same div.

$("#button1").click(function(){
    $('#div1').load('page1.php');
});


$("#button2").click(function(){
    $('#div1').load('page2.php');
});

<div id="div1">      </div>

Is there any other way to do this?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

Option 1:

If your buttons and pages are actually numbered like that, you can simply extract the number from the ID:

var $container = $('#div1');

$('[id^=button]').click(function() {
    $container.load('page' + this.id.match(/\d+$/)[0] + '.php');
});

Option 2:

If that was just an example, but in reality your naming scheme is not so predictable, you can keep an object map with all the appropriate URLs:

var $container = $('#div1'),
    map = {
        button1: 'page1',
        button2: 'page2'
        // and so on...
    };

$('[id^=button]').click(function() {
    $container.load( map[ this.id ] );
});

Option 3:

You could store the page URL in the HTML:

<div id="button1" data-page="page1"></div>
<div id="button2" data-page="page2"></div>

and then use that in your JavaScript:

var $container = $('#div1');

$('[id^=button]').click(function() {
    $container.load( $(this).attr('data-page') );
});

I personally dislike this method, since it puts behavioral stuff in your HTML.

share|improve this answer
    
wooow ! Thanks for showing many many ways of doing it :) . – jathin Jul 26 '12 at 4:58
    
I like the 3rd method best, since it allows you to give your PHP files better names than numbering them, it places the all the relevant data into the HTML (where is belongs) and if you ever change any links you don't need to touch the JavaScript. – RoToRa Jul 26 '12 at 13:26
    
NB: I just saw an error in your case 3: You are using classes in the HTML, but are selecting by ID in the script. – RoToRa Jul 26 '12 at 13:27
    
@RoToRa - Thanks for spotting that. Updated. I personally prefer using classes, but since the OP is using IDs I'll stick to that. – Joseph Silber Jul 26 '12 at 17:47
    
I'd probably add a class to the html and select using that, instead of using a slow attribute selector. – Inkbug Jul 27 '12 at 7:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.