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:
- Looks for links with a class of ‘tour’ and defines 3 more variations of its href attribute (swapping out a 4-digit number).
- Replaces links with a class of ‘tour’ with different content that substitutes in the additional 4-digit values.
- 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 & 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>
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 inaudyou can use that:Note that your code will update (replace) all
.tourlinks using theaud,usd, etc. values from the first.tourlink. Is that what you intend, or should it update them individually?