Question

how to shorten the code? He wants to apply the principle of DRY? Here code:

$('a[href^="#register"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load('register.html');
    e.preventDefault();
});

$('a[href^="#blog"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load('blog.html');
    e.preventDefault();
});

$('a[href^="#contact"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load('contact.html');
    e.preventDefault();
});

Please help :)

Was it helpful?

Solution 2

apply class on anchor tags and write event on class like this:

$('a.MyClass').click(function(e){


$('.box').addClass('active');
$('.box div').load($(this).attr("href").split('#')[1]+'.html');
e.preventDefault();


});

OTHER TIPS

Try something like:

$('a[href^="#register"], a[href^="#blog"], a[href^="#contact"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load(this.getAttribute('href').split('#')[1]+'.html');
    e.preventDefault();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top