Switching the image by clicking on the link

Looking for assistance with a code that displays three button images and fades in the relevant div when clicked using jQuery...

http://jsfiddle.net/ttj9J/11/

HTML

<a class="link" href="#" data-rel="content1"><img src="http://i.imgur.com/u1SbuRE.png"></a>
<a class="link" href="#" data-rel="content2"><img src="http://i.imgur.com/RxSLu4i.png"></a>
<a class="link" href="#" data-rel="content3"><img src="http://i.imgur.com/U8Jw3U6.png"></a>


<div class="content-container">
    <div id="content1">This is the test content for part 1</div>
    <div id="content2">This is the test content for part 2</div>
    <div id="content3">This is the test content for part 3</div>
</div>

CSS

.content-container {
    position: relative;
    width: 400px;
    height: 400px;
}
.content-container div {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

JQUERY

$(".link").click(function(e) {
      e.preventDefault();
      $('.content-container div').fadeOut('slow');
      $('#' + $(this).data('rel')).fadeIn('slow');

});

$( document ).ready(function() {
    $(".link")[0].click(); 
});

Want to change button images to these when clicked:

http://i.imgur.com/vi1KLp9.png
http://i.imgur.com/syroxDR.png
http://i.imgur.com/l91OpLL.png

Can anyone provide guidance on this?

Answer №1

One effective strategy is to keep all display code within CSS and structure your HTML for more intuitive functionality. This means that by looking at the HTML code alone, you can easily see if a button has been pressed by checking if the 'Down' class has been added to it.

CSS:

        .redButton > div
        {
            background-image: url('http://i.imgur.com/u1SbuRE.png');
        }
        .redButton.Down > div
        {
            background-image: url('http://i.imgur.com/vi1KLp9.png');
        }
        .link > div
        {
            width: 88px;
            height: 88px;
            display:inline-block;
        }

JavaScript:

 $(".link").click(function(e) {
             e.preventDefault();

             var mainButton = $(e.target).parent();

             $('.link').not(mainButton).removeClass('Down');  

             mainButton.toggleClass('Down');
             $('.content-container div').fadeOut('slow');    
             $('#' + $(this).data('rel')).fadeIn('slow');        
             });

HTML:

 <a class="link redButton" href="#" data-rel="content1">
        <div></div>
        </a>
    <div class="content-container">
        <div id="content1">This is the test content for part 1</div>
    </div>

Avoid the need to manage an image array in JavaScript (yuck). By utilizing each layer of the HTML stack correctly, you maintain cleaner code and improved functionality.

Check out the jsFiddle Hot Demo for a live example.

Answer №2

Give this a try:

var imageCollection = [
    'http://i.imgur.com/vi1KLp9.png',
    'http://i.imgur.com/syroxDR.png',
    'http://i.imgur.com/l91OpLL.png'
];

$(".link").click(function(e) {
      e.preventDefault();
      // Update the image source.
      $(this).find('img').prop('src', imageCollection[$(this).index()]);

      $('.content-container div').fadeOut('slow');
      $('#' + $(this).data('rel')).fadeIn('slow');
});

View JSFiddle Demo

Additional Information #2:

If you want to revert other images when clicking on one, save the default image sources initially:

var imageCollection = [
    'http://i.imgur.com/vi1KLp9.png',
    'http://i.imgur.com/syroxDR.png',
    'http://i.imgur.com/l91OpLL.png'
], defaultImages = [];

$('.link').find('img').each(function(){
    defaultImages.push($(this).prop('src'));
});

$(".link").click(function(e) {
    e.preventDefault();
    
    $(".link").find('img').each(function(i) {
        $(this).prop('src', defaultImages[i]);
    });

    $(this).find('img').prop('src', imageCollection[$(this).index()]);

    $('.content-container div').fadeOut('slow');
    $('#' + $(this).data('rel')).fadeIn('slow');
});

View Updated JSFiddle Demo

Further Update #3:

If using imageCollection to store new src attributes seems too complex, you can utilize data-* attributes for storing the src, like:

data-newsrc="path/to/new/src"
. Then access it easily with $(selector).data('newsrc');

$(this).find('img').prop('src', $(this).find('img').data('newsrc'));

View Third JSFiddle Demo

Answer №3

Click here for the code on JSFiddle

JavaScript:

$(".link").click(function(e) {
      e.preventDefault();
      $('.content-container div').fadeOut('slow');

      //retrieve src for the new img
      var new_img_src = $(this).data('newimg');
      var current_img = jQuery("img", this);

      //swap data-newimg src with current src
      $(this).data('newimg', current_img.attr("src"));    
      current_img.attr("src",new_img_src);

      $('#' + $(this).data('rel')).fadeIn('slow');     
});

HTML:

<a class="link" href="#" data-rel="content1" data-newimg="http://i.imgur.com/vi1KLp9.png">
    <img src="http://i.imgur.com/u1SbuRE.png">
</a>
<a class="link" href="#" data-rel="content2" data-newimg="http://i.imgur.com/syroxDR.png">
    <img src="http://i.imgur.com/RxSLu4i.png">
</a>
<a class="link" href="#" data-rel="content3" data-newimg="http://i.imgur.com/l91OpLL.png">
    <img src="http://i.imgur.com/U8Jw3U6.png">
</a>

<div class="content-container">
    <div id="content1">This is the test content for part 1</div>
    <div id="content2">This is the test content for part 2</div>
    <div id="content3">This is the test content for part 3</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Center text vertically even when its number of lines is unknown

Can anyone help me figure out how to vertically center text that can be one or two lines long? The text also has a specific line-height set. I attempted the solution provided in this link but it didn't produce the desired result: <div> < ...

What is the best way to design a large grid layout using HTML5?

I am aiming to construct a 6 by x grid where the columns retain uniform size based on the width of the outer container (i.e. body). The height should be consistent within each row and adjust according to the content in each cell. Below is my current progr ...

Making use of JavaScript's XMLHttpRequest() function allows for seamless

My issue revolves around my use of multiple XMLHttpRequest() requests in order to retrieve the value (miniTable) returned by the TableRow() function. Strangely, while I get the desired value when using alert() at the end of the TableRow() function, the T ...

Conceal the overflow from absolutely positioned elements

I've gone through all the similar examples but still struggling to find the correct solution. My issue involves a basic Side Menu that toggles upon button click. Within the menu, there is a list of checkboxes positioned absolutely with the parent con ...

Modify the value of a variable every 250 milliseconds

Currently working on a game website and stuck at the registration stage. We are looking to allow players to input a code in their Ingame notes for verification purposes. I have created a PHP class to retrieve the ingame notes, but now I need to set a java ...

What is the reason behind jQuery's .html("abc") only providing temporary insertion?

I have come across an issue with an HTML button that triggers a function. Whenever the button is clicked, a div is inserted but it only appears for a brief moment before disappearing both visually and in the HTML tree. function openBox () { $( '#0&a ...

Discovering a particular string within a jQuery array object: Tips and tricks

One thing that is confusing me is the jQuery array object. To explain further: I have two arrays, one called brandsLink and the other called floorLink. When a user clicks on a link, I am saving the brand name in a variable called brandName, and then checki ...

Leveraging Javascript to generate universal HTML content for various Javascript files

Present Situation: I have a timesheet feature that enables users to input their leave, TOIL, and sick days along with the respective hours. Additionally, there is a table that dynamically adds a new row every time the plus button is clicked using the foll ...

How can I find the hexadecimal color value from this jQuery plugin?

Hey everyone, I've been using this awesome jQuery plugin for a color picker. However, I'm curious about where the hex value of the chosen color is stored when the user selects it. I need to process it and save it to the database. Thanks! If you& ...

What is the best way to set breakpoints on Material UI components?

Currently, I am exploring material-ui and I'm curious if there is a way to set all breakpoints at once. The code snippet below seems quite repetitive. Is there a more efficient method to achieve this? <Grid xs={12} sm={12} md={12} lg={12} xl={12} ...

Utilize the DataTables plugin to arrange a column based on icons with hidden boolean values in rows

I am currently utilizing the DataTables plugin to enhance my HTML table. While I have managed to successfully implement most functionalities, I am facing a challenge with the boolean column. This particular column consists of icons representing X (value 0) ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

Displaying PHP output within a JavaScript expression

Let's dive into a scenario involving a basic HTML document and some JavaScript that's loaded within it: <!-- doc.html --> <!doctype html> <html lang="en"> <head> <script type="text/javascript" src=" ...

How can I troubleshoot an image not appearing in Bootstrap within a Laravel Blade file while using PHPStorm?

Forgive me if this sounds like a silly question: I attempted to use the following src attribute in an img tag to show an image on a website created with Bootstrap, while using phpstorm with a laravel blade file: src="C:\Users\MAHE\Pictures&b ...

Creating text input without borders using HTML and CSS

I have managed to create text inputs without borders using HTML and CSS, but I am facing an issue. Whenever I click on the input field, a yellow border appears instead of the one I removed. It seems like this is coming from the default stylesheets, and I&a ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Tips for retrieving a collection of nodes using a specific CSS selector in jQuery

How can I select a set of nodes using a CSS selector in jQuery? In YUI, this is accomplished with YAHOO.util.Selector.query(abc, root), where abc represents the CSS. Can anyone help me convert this functionality to jQuery? ...

developing a dropdown menu feature

I'm struggling with a small issue related to my drop-down menu function. My goal is to hide the visibility of a menu tab after it has been clicked for the second time. Below is the code snippet I've been working on: HTML:- <nav class="clea ...

The li elements within a 960.gs layout will not extend to fill the entire width of the

I am still learning about this and I have been following some tutorials online. I managed to make the columns work with paragraph tags, but when I use ul > li tags, the image takes up the entire space. I'm not sure what's causing this issue. Wha ...

Submitting forms with Ajax

Hi everyone, I'm encountering an issue with the post data not appearing as expected and it seems like the functionality is not working properly. The main requirement was for it to trigger an accept/deny action with an attached id number and a value fo ...