0

Can someone help me write a jQuery script to replace a div class to another class when a link is clicked. I have a list of addresses, and I want a map image to change when an address is clicked. Due to the structure of the css and gradients on the image, simply changing the backround-image url won't help. I am creating 4 classes for each of the addresses, each with the background image that image of each address.

I have simplified my code so that it is easier to write a script. This is what I have built:

The image wrapper:

<div class="map-wrapper map1">
</div>

The address list:

<ul>
    <li><a href="#map1">Address 1</a></li>
    <li><a href="#map2">Address 2</a></li>
    <li><a href="#map3">Address 4</a></li>
    <li><a href="#map4">Address 5</a></li>
</ul>

The jQuery I had before, when I simply changed an within the map-grad tags.

 var itemInfo = { // Initialise the item information
      img1: ['/img/map.png', ''],
      img2: ['/img/ealing_map.jpg', ''],
};

$(function() {
      $('#maps a').click(function() { // When an item is selected
            var id = $(this).attr('href').replace(/#/, ''); // Retrieve its ID
            $('#info img').attr('src', itemInfo[id][0]); // Set the image
            $('#info p').text(itemInfo[id][1]); // And text
            return false; // Prevent default behaviour
      });
});

I want to write a jQuery script that changes the class 'map1' to 'map2, 3 or 4' when the relevant address link is clicked. This in turn will change the background image! :)

So, can anyone please help me! I am a javascript and jQuery newbie and know not an awful lot!

1
  • 1
    What is #maps? The <ul>? Commented Jun 16, 2013 at 12:56

3 Answers 3

2
$('ul li a').on('click', function(e) {
    e.preventDefault();
    var cl = $(this).attr('href').replace('#','');
    $('.map-wrapper').removeClass().addClass('map-wrapper '+cl);
});

FIDDLE

Sign up to request clarification or add additional context in comments.

2 Comments

@LightStyle - just noticed it myself, typing to fast I guess, thanks!
It can happen sometimes, don't worry :D +1!
0

You need something like

$('.map-wrapper').removeClass().addClass('map-wrapper '+$(this).attr('id'));

Comments

0

Add the following add the end of your function:

$(".map-wrapper").removeClass("map1 map2 map3 map4").addClass(id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.