javascriptless
javascriptless

Reputation: 233

How do I simplify this repetitive jquery code?

I made a jQuery script that works fine, I'd just like to see if anyone had tips on simplifying it, in particular the beginning part in which variables are defined.

Though I'm really interested in straight code simplification, here's a quick synopsis on what the script actually does:

  1. Looks for links with a class of 'tour' and defines 3 more variations of its href attribute (swapping out a 4-digit number).
  2. Replaces links with a class of 'tour' with different content that substitutes in the additional 4-digit values.
  3. With a.tour replaced, visibility of part of the content is toggled on hover.

And here's the code:

HTML:

<a href="http://www.awebsite.com/7838" class="tour">Link</a>

JQUERY:

<script>
$(document).ready(function() {
    var aud = $('.tour').attr('href');
    var usd = $('.tour').attr('href').replace(7838,'8062');
    var gbp = $('.tour').attr('href').replace(7838,'8907');
    var eur = $('.tour').attr('href').replace(7838,'8914');
    $('.tour').replaceWith('<div class="currency"><p>Price &amp; Bookings</p><ul class="currencydd" style="display:none"><li><a href="' + aud + '">Australian Dollar (AUD)</a></li><li><a href="' + usd + '">United States Dollar (USD)</a></li><li><a href="' + gbp + '">British Pounds (GBP)</a></li><li><a href="' + eur + '">Euros (EUR)</a></li></ul></div>');
    $('.currency').hover(function () {
  $('.currencydd').slideToggle("fast");
});
});

</script>

Upvotes: -1

Views: 216

Answers (6)

adeneo
adeneo

Reputation: 318342

$(document).ready(function() {
    var ref = $('.tour').attr('href');
    function G(t) {return ref.replace(7838, t=='eur'?'8914':t=='usd'?'8062':t=='gbp'?'8907':'7838');}
    $('.tour').replaceWith('<div class="currency"><p>Price &amp; Bookings</p><ul class="currencydd" style="display:none"><li><a href="' + G('aud') + '">Australian Dollar (AUD)</a></li><li><a href="' + G('usd') + '">United States Dollar (USD)</a></li><li><a href="' + G('gbp') + '">British Pounds (GBP)</a></li><li><a href="' + G('eur') + '">Euros (EUR)</a></li></ul></div>');
    $('.currency').hover(function () {
        $('.currencydd').slideToggle("fast");
    });
});​

FIDDLE

Upvotes: 0

elclanrs
elclanrs

Reputation: 94131

This is not shorter but definitely more optimized and more extensible. Untested:

var href = $('.tour').attr('href'),
    items = '',
    currency = {
        aud : {
            name : 'Australian Dollar',
            value : 1
        },
        usd : {
            name : 'United States Dollar',
            value : 1.05
        },
        eur : {
            name : 'Euros',
            value : 0.8
        },
        gbp : {
            name : 'British Pounds',
            value : 0.67
        }
    }

for (var c in currency) {

    var num = href.match(/\d+/), // Simple regex, maybe too simple...
        conv = Math.ceil(currency[c].value * num),
        url = href.replace(num, conv);

    items += '<li>' +
        '<a href="' + url + '">' +
            currency[c].name + ' (' + c.toUpperCase() + ')' +
        '</a>' +
    '</li>';
}

$('.tour').replaceWith('<div><ul>' + items + '</ul></div>');

Upvotes: 0

Mike Lin
Mike Lin

Reputation: 370

2 suggestions:

1: write a function for url transformation such as

function currencyExchange(srcUrl){
 return srcUrl.substring(0,preLength) + rate * Number(src.substring(preLength));
}

2: using javascript template technique to simply the new element construction.

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150070

Don't keep using $(".tour") over and over, it is both neater and more efficient to define a variable equal to it. Also, you don't need to keep checking the .attr("href") because once you've stored that value in aud you can use that:

var $tour = $(".tour"),
    aud = $tour.attr('href'),
    usd = aud.replace(7838,'8062'),
    gbp = aud.replace(7838,'8907'),
    eur = aud.replace(7838,'8914');

$tour.replaceWith(...);

Note that your code will update (replace) all .tour links using the aud, usd, etc. values from the first .tour link. Is that what you intend, or should it update them individually?

Upvotes: 0

Manishearth
Manishearth

Reputation: 16198

var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var usd = treplace('8062');
var gbp = treplace('8907');
var eur = treplace('8914');

Even better, you can do something like this if you want lots of currencies

var abbrev=["USD","GBP","EUR"]
var codes=[8062,8907,8924]
var names=["US Dollar","British Pounds","Aussie Dollar"]
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var s='<div class="currency"><p>Price &amp; Bookings</p><ul>';
for(i in abbrev){
 //build the rest of the HTML here, using the arrays

}
s+='</ul></div>'
$('.tour').replaceWith(s)

You could also use a 2D array or a custom object instead of three arrays.

Upvotes: 0

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

well for starters you could have the following:

var $aud = $('.tour').attr('href'),
    $usd = $aud.replace(7838,'8062'),
    $gbp = $aud.replace(7838,'8907'),
    $eur = $aud.replace(7838,'8914');

Upvotes: 0

Related Questions