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

Learning how to invoke a JavaScript function from a Ruby on Rails layout

In the file app/views/download.js.erb, I have defined a javascript function named timeout(). This function continuously polls a specific location on the server to check if a file is ready for download. I am currently running this function as a background ...

Why is the Bootstrap tooltip flickering and not closing on mouseout? And why are duplicate entries not being triggered?

I'm facing some issues with the code I have here: Check it out The problems are as follows: Flickering - When hovering over the images slowly, there is noticeable flickering in the tooltip box rendering 2-3 times. This seems to be related to the cla ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

Using jQuery and AJAX to fetch the return value of a PHP class method

Starting a new project for myself has been quite the learning experience. As someone who isn't the most skilled programmer, I decided to kick things off in PHP. However, I quickly realized that executing PHP functions and class methods through HTML bu ...

How can I create my own unique scrolling behavior in JavaScript?

Looking to create a similar effect as seen on this website: where the vertical scrollbar determines the movement of the browser "viewport" along a set path. I believe that using Javascript to track the scroll bar value and adjust background elements acco ...

Does Javascript support annotation? If not, what is the best way to easily switch between debug and productive modes in a declarative manner?

I have a question that has been on my mind. I have searched Google but couldn't find any helpful links, so I thought it would be best to seek advice from experts here. My main concern is whether there is a way to create annotations in JavaScript sour ...

Issue with Jquery ajax functionality

I have a clickable map of a country that is loaded when the document is ready. $(document).ready(function bg() { $.ajaxSetup ({cache: false,timeout: 5000}); $("#map").load("/maps/country.php",function() { $('.map').m ...

Having trouble with button styling, unsure how to fix it

As someone who is new to learning, I am currently struggling with styling a button on my website. No matter what I try, it remains a white rectangle with just a border and some text. I have included the code for reference. Any help or advice would be great ...

Having trouble getting the form to submit with jQuery's submitHandler

I am in the process of converting a contact form to AJAX so that I can utilize the success function. Currently, I am encountering an issue where the code is halting at the submitHandler section due to it being undefined. Can anyone identify why my submitHa ...

Combining two CSS classes to create an "alias"

Currently, Iā€™m utilizing bootstrap for table styling. For instance: <table class="table table-striped main"> However, the table I want to style is dynamically generated by a separate tool that I have no control over, and it already has its own ta ...

Secondary navigation bar remains hidden

I am facing an issue with the sub menu bar on this website. I am using the Constellation theme for WordPress and have attempted to adjust margins in order to make it visible, but so far I have been unsuccessful. The sub menu is meant to be responsive, yet ...

Angular application not displaying refreshed data after fetching information from the server

I've developed a report generator in AngularJS that functions well without using the jQuery datepicker. However, when I implement the jQuery datepicker, the data retrieved from the server is accurate, but the front-end doesn't reflect the changes ...

Tips for concealing a div using an article until it is activated by hovering over it

I am looking to incorporate a sleek sliding animation on an article that reveals more information in a div upon mouseover. A great example of this can be seen on where clicking at the top right corner triggers the "Show Modern Dev Ad" feature. Below is m ...

Utilize JavaScript/jQuery to implement a prompt for saving downloaded files

Is it possible to use javascript or jquery to configure the setting mentioned above (Ask where to save each file before downloading)? ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...

Is it simple to customize the color of the close button in Bootstrap 5?

Bootstrap's v5 release brings updated styling to various components, including the close button. In previous versions, the close button had an "x" that could be easily styled with text properties, like inheriting color from its parent. However, in v5, ...

The appearance of all input forms in MaterializeCSS when used in an electron environment appears to

After following the instructions here on how to get started with Materialize CSS, I am having issues with my input form appearing strange: The contents of my current index.html file are as follows: <!DOCTYPE html> <html> <head> & ...

Using PHP and JQuery to send two variables via the post method

I've been attempting to send two variables from two input fields using jQuery to a PHP page, but I'm having trouble retrieving the data. It seems to work fine when I only have one variable, but as soon as I try with two, it doesn't seem to w ...

Creating a customizable date format feature in Spring MVC and jQuery

Exploring different methods to configure date formats for the application via a properties file. Considering implementing a conversion service in Spring along with a model serving as the date format property for jQuery datepicker. However, I encountered ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...