Nick
Nick

Reputation: 2549

jQuery - Add Code To A Function To Simplify (Stop Repeating Similar Things)

I'm new to jQuery - So I apologise if this is a silly question :)

I've been challenged with making the code my team uses simple enough to allow less "skilled" people to update it.

I've set variables for everything that needs changing and it works as I expect it to.

My only query is that I'll be running the same 4 things over and over again and I feel like I could achieve what I want in a function?

Here's a fiddle of it in action with 3 different banners: http://jsfiddle.net/8ez46mpg/

I repeat this several times over targeting different banners:

var $primaryBanner1 = $('#banner-01');
$primaryBanner1.attr('title', primaryOneTxt);
$primaryBanner1.html("<h2>" + primaryOneTxt + "</h2>");
$primaryBanner1.attr('href', primaryOneUrl);
$primaryBanner1.css("background", "url("+primaryOneImg+")");

Is there any way I could simplify this into a smaller function? Rather than having the same 4 lines up to 15 times per page?

Any help would be really great!

Thanks!

Upvotes: 0

Views: 57

Answers (1)

Rob M.
Rob M.

Reputation: 36511

Just make a function that performs the repetitive actions and pass in the dynamic variables.

function styleBanner(selector, txt, url, img){
  var $el = $(selector);
  $el.attr({
    title: txt,
    href: url
  }).css('background', 'url('+img+')')
    .html('<h2>'+txt+'</h2>');

  return $el;
}

var $primaryBanner1 = styleBanner('#banner-01', primaryOneTxt, primaryOneUrl, primaryOneImg);

Upvotes: 3

Related Questions