views:

157

answers:

2

I have 3 divs with 2 possible image tags for each (active or inactive). If one div is clicked to be active the other divs must be set to inactive. How do I accomplish this with img tags and what happens if user has javascript disable?

+1  A: 

if a user has JavaScript disabled, there is nothing you can do that is JavaScript-based to deal with dynamically modifying the page. The only other option you have is to create a "deprecated" version of your functionality that requires a page request after each click.

I would recommend researching how to dynamically add/remove classes from elements in the DOM, that is how I would approach this problem. You could easily do a jQuery select for all elements who are "active" on click and set a "disabled" class on them, that way you are essentially blacking out everything except the element you've clicked.

Does that make sense?

Derek P.
so i would put all both active and inactive image tags in html. and add remove classes to disable them? Or so as above and specify src when they are clicked?
zsharp
+3  A: 

Do you mean something like this?

<div class="block" id="block1">
    <img src='inactive_block1.jpg'>
</div>

<div class="block" id="block2">
    <img src='inactive_block2.jpg'>
</div>

<div class="block" id="block3">
    <img src='inactive_block3.jpg'>
</div>

Using a library like jQuery, the javascript would look like:

$(function() {
    $('.block').click(function() {
       $('#block1').find('img').attr('src', 'inactive_block1.jpg');
       $('#block2').find('img').attr('src', 'inactive_block2.jpg');
       $('#block3').find('img').attr('src', 'inactive_block3.jpg');
       $(this).find('img').attr('src', 'active_' + $(this).attr('id') + '.jpg');
    });
});

With the above, if you have inactive_block1.jpg, inactive_block2.jpg, inactive_block3.jpg and active_block1.jpg, active_block2.jpg and active_block3.jpg you should get what you want.

It's up to you whether its worth it or not to have javascript disabled fallbacks, mostly depending on whether you expect a large amount of your audience to have javascript disabled.

Paolo Bergantino
within each div i want there to be an img tag, not a css background.
zsharp
updated my answer to work with images :)
Paolo Bergantino
thanks, but one other twist... the inactive and active jpg are not the same in each div..
zsharp
... updated again.
Paolo Bergantino
gave the credit, but it didnt actually toggle images.
zsharp
Oops. I had a couple of errors in it. Fixed it. Try it now. Both the html and the javascript changed, so yeah.
Paolo Bergantino