Alter images by selecting a specific text to trigger the change

I have a description of animals in a list

<ul class="1">
  <li class="liHEADER">ANIMALS</li>
    <li class="animalss">LION</li>
    <li class="animalss">TIGER</li>
    <li class="animalss">CHEETAH</li>
</ul>

Additionally, I have specific <div> elements for each animal's picture and label

<div class="show">   
  <div class="pic"><img src="LION.jpg"></pic>
  <div class="labels">LION</div>

  <div class="pic"><img src="TIGER.jpg"></pic>
  <div class="labels">TIGER</div>

  <div class="pic"><img src="CHEETAH.jpg"></pic>
  <div class="labels">CHEETAH</div>
</div>

I am looking to implement functionality where clicking on an animal name shows the corresponding image and label. Is there a way to achieve this using JavaScript or jQuery?

I appreciate any help as I am not very experienced with this.

Answer №1

Discover a new solution!

Check out the Js Fiddler Demo here

HTML Code

<ul class="1">
  <li class="liHEADER">ANIMALS</li>
   <li class="animalss">LION</li>
   <li class="animalss">TIGER</li>
   <li class="animalss">CHEETAH</li>
</ul>

    <div class="show">   
    <div class="pic" data-name="lion"><img  src="http://rs183.pbsrc.com/albums/x46/rebelrhoads/Lion.jpg~c200"/></div>
 <div class="labels" data-name="lion">LION</div>

 <div class="pic" data-name="tiger"><img src="http://www.perthzoo.wa.gov.au/wp-content/uploads/2011/06/Sumatran-Tiger.jpg"/></div>
 <div class="labels" data-name="tiger">TIGER</div>

 <div class="pic" data-name="cheetah"><img src="http://blog.londolozi.com/wp-content/uploads/2013/11/thumb-cheetah.jpg"/></div>
 <div class="labels" data-name="cheetah">CHEETAH</div>
</div>

CSS Styling

li{
color:#999;
cursor:pointer;
 }
  li.selected{
  color:#000;
 }
li:hover{
color:#000;
}

div.pic, div.labels{
display:none;
}

JavaScript Logic

$(function(){
        $('li').click(showAnimal);
});

function showAnimal(){
       $('li').removeClass('selected');
        $(this).addClass('selected');

        var animal = $(this).text();

        if(animal.toString().toLowerCase() == "animals")
            $('div[data-name]').show();
        else{
            $('div.pic').hide();
            $('div.labels').hide();

            $('div[data-name=' + animal.toString().toLowerCase() + ']').show();
        }
}

Answer №2

Here is the concept I came up with:

html

<div class="display">   
  <div class="photo lion"><img src="LION.jpg"></img>
  <div class="labels lion">LION</div>

  <div class="photo tiger"><img src="TIGER.jpg"></img>
  <div class="labels tiger">TIGER</div>

  <div class="photo cheetah"><img src="CHEETAH.jpg"></img>
  <div class="labels cheetah">CHEETAH</div>
</div>

javascript

 $(function(){
    $('.animals').click(function(){
      switch($(this).text()){
        case 'LION': 
           $('.photo').not('.lion').hide();
           $('.labels').not('.lion').hide();
           $('.lion').show();
        break;
        case 'TIGER': 
           $('.photo').not('.tiger').hide();
           $('.labels').not('.tiger').hide();
           $('.tiger').show();
        break;
       case 'CHEETAH': 
           $('.photo').not('.cheetah').hide();
           $('.labels').not('.cheetah').hide();
           $('.cheetah').show();
        break;
      }
    });
});

Answer №3

Check out this sample code:

HTML

<label>ANIMALS</label>
<ul class="1">
    <li class="animalss">LION</li>
    <li class="animalss">TIGER</li>
    <li class="animalss">CHEETAH</li>
</ul>

<div class="show">
 <div class="lion" style="display:none">   
   <div class="pic"><img src="LION.jpg"></div>
  <div class="labels">LION</div>
 </div>
 <div class="tiger" style="display:none">  
  <div class="pic"><img src="LION.jpg"></div>
  <div class="labels">TIGER</div>
</div>
<div class="cheetah" style="display:none">  
  <div class="pic"><img src="LION.jpg"></div>
  <div class="labels">CHEETAH</div>
</div>      
</div>

Jquery Script

$('ul li').on('click',function(){
   var text=$(this).text().toLowerCase();
   $('.'+text).show('slow').siblings().hide();
});

View the DEMO here

Answer №4

//take a look at the demo on fiddle DEMO http://jsfiddle.net/5Ks5n/

html

<ul class="animal-list">
    <li class="liHEADER" data-view="lion">Lion</li>
    <li class="animalss" data-view="tiger">Tiger</li>
</ul>

<div class="show">   
      <div class="pic" style="display:none" data-animal="lion">
          <img src="http://3.bp.blogspot.com/-OiigZsVwwNQ/UFM5KDugeiI/AAAAAAAAJ_Y/HrPEPFnSXCI/s1600/Male+Lion+Wallpapers+1.jpg" />
      <div class="labels">LION</div>
    </div>

    <div class="pic" style="display:none" data-animal="tiger">
        <img src="http://3.bp.blogspot.com/-OiigZsVwwNQ/UFM5KDugeiI/AAAAAAAAJ_Y/HrPEPFnSXCI/s1600/Male+Lion+Wallpapers+1.jpg" />
        <div class="labels">TIGER</div>
    </div>
</div>

Javascript

$(document).on("click",".animal-list",function(element){
    var $target = $(element.target);
    var animal = $target.attr("data-view");
    $(".pic").hide();
    $("[data-animal='"+ animal +"']").show();
});

Answer №5

Effortless method:

  <label>CREATURES</label>
  <ul class="1">
    <li class="animalss">ELEPHANT</li>
    <li class="animalss">GORILLA</li>
    <li class="animalss">RHINOCEROS</li>
  </ul>

  <div class="show">
    <div class="elephant_pic" style="display:none">
      <img src="ELEPHANT.jpg"></pic>
      <label>ELEPHANT</label>
    </div>
    <div class="gorilla_pic" style="display:none">
      <img src="GORILLA.jpg"></pic>
      <label>GORILLA</label>
    </div>
    <div class="rhinoceros_pic" style="display:none">
      <img src="RHINOCEROS.jpg"></pic>
      <label>RHINOCEROS</label>
    </div>
  </div>

JavaScript Function:

  $('ul.1').click(function(e){
    var category = $(e.target).text();
    if(category === 'ELEPHANT'){
      $('.elephant_pic').show();
      $('.gorilla_pic').hide();
      $('.rhinoceros_pic').hide();
    } else if(category === 'GORILLA'){
      $('.gorilla_pic').show();
      $('.elephant_pic').hide()
      $('.rhinoceros_pic').hide()
    } else {
      $('.rhinoceros_pic').show();
      $('.elephant_pic').hide()
      $('.gorilla_pic').hide()
    }
  });

Answer №6

To make this process easier, one method is to assign classes to a group, where each class represents elements that interact with each other such as text, images, and labels. Here is an example of how you can structure your code:


 <pre>
<style>
.show div{display:none;}
</style>
    <ul class="1">
      <li class="liHEADER">ANIMALS</li>
        <li class="animalss" id = "lion" onclick="showImage(this.id);">LION</li>
        <li class="animalss" id = "tiger" onclick="showImage(this.id);">TIGER</li>
        <li class="animalss" id="cheetah" onclick="showImage(this.id);">CHEETAH</li>
    </ul>

    <div class="show">   
      <div class="pic lion"><img src="LION.jpg"></pic>
      <div class="labels lion">LION</div>

      <div class="pic tiger"><img src="LION.jpg"></pic>
      <div class="labels tiger">TIGER</div>

      <div class="pic cheetah"><img src="LION.jpg"></pic>
      <div class="labels cheetah">CHEETAH</div>
    </div>
</pre>

Next, the jQuery code would be:

<pre>
<script>
function showImage(param){
  var classToShow = param;
  $('.'+param).show();
  $('.show div:not("."'+param+'")').hide();
}
</script>
</pre>

Please review for any syntax errors and inform me if any are found.

Answer №7

I have restructured the HTML for better clarity and ease of understanding, assuming that you have the ability to modify your website's code. This is a common way to format code for creating Tabs.

<ul>
    <li class="animals"><a href="#lion">LION</a></li>
    <li class="animals"><a href="#tiger">TIGER</a></li>
</ul>
<div class="content">   
    <div class="pic" id="lion">
        <img src="LION.jpg" />
        <div class="labels">LION</div>
    </div>
    <div class="pic" id="tiger">
        <img src="TIGER.jpg" />
        <div class="labels">TIGER</div>
    </div>
</div>

Below is the jQuery code snippet,

$(".pic").hide();
$("a[href='#lion']").on('click', function() {
    $(".pic").hide();
    $("#lion").show();    
});
$("a[href='#tiger']").on('click', function() {
    $(".pic").hide();
    $("#tiger").show();    
});

Upon page reload, we ensure that all images are hidden using $(".pic").hide(). Subsequently, when the user clicks on either LION or TIGER links, both images will be hidden and only the relevant one (LION or TIGER) will be shown. Here is a Live Demo. While it's possible to condense the code further by abstracting ANIMALS instead of LION and TIGER, this may increase complexity especially for beginners.

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

Reorganizing an array of JSON data by date value with a limitation to just one

Currently, I am attempting to organize a JSON array based on the date key. However, it appears that my sorting function is either stopping after one sort or simply not functioning correctly. Here is the JavaScript code for my sorting function: function ...

Proceed to the section with modal

My goal is to create a modal with 4 sections, each loading its content dynamically using the .load() function to the container on the right side. The challenge I'm facing is that I have a footer menu that triggers the modal to open, and I need it to ...

Determine the React component's position in relation to the viewport while scrolling, ideally in percentage

I'm searching for effective solutions to solve this issue that has me stumped, and haven't come across any suitable libraries. What I'm looking for specifically is a way to track a Component's vertical position (Y) when scrolling, but ...

Embedding images within written content

Is there a way to insert an image into text from a specific position without using tables? I'm looking for a method other than aligning the image "left or right". https://i.sstatic.net/8gvxk.png ...

Conceal the scrollbar when the expansion panel is in its collapsed state

One issue I am encountering is that the scroll-bar appears when the expansion panel is collapsed, but not when it's expanded. Here are the references: Collapsed Expanded <mat-expansion-panel class="panel"> <mat-expansion-panel-he ...

Alter div elements with jQuery based on the particular link that was selected

I'm struggling with updating a nav bar that has different divs based on the link clicked. <script> $(document).ready(function (){ $("#content").load("content/index_content.php"); $('a').click(function(){ $ ...

I can't figure out why the callback function for my $.get() request is not being triggered when I send data to the Express

Could anyone help me understand why my callback function is not being called properly? $.get("http://localhost:8080/", msg, function(data) { alert("Data" + data); }); It seems like the server receives the reque ...

Designing an advanced remote upload system using jQuery AJAX and PHP

Currently, I am in the process of developing an image hosting script and everything is going smoothly so far. To enable local uploading with drag & drop + AJAX, I have utilized various plugins which are working perfectly. Now, I am moving on to implementin ...

City-based Address Suggestions with Google API Places

I have been struggling to find a solution to this specific issue without any luck. Your assistance would be greatly appreciated. Currently, I am attempting to implement autocomplete address functionality using Google API with the following code: var inpu ...

Issue with ng-repeat directive not functioning

Let's dive into this directive: .directive('img', function () { return { restrict: 'E', link: function (scope, elem, attr) { if (attr.src && attr.type === "extension"){ var ...

Is there a way to determine whether an object possesses a specific property or not?

Searching for a solution that works across various browsers to determine whether an object contains a specific property. For example, let's say we have a span element: var elem = document.getElementById('span1'); if(elem.hasOwnProperty(&a ...

How can data be transferred from child component inputs to a parent form in Angular's template-driven approach?

It seems like this should be a straightforward task, but I'm encountering conflicting instructions on how to achieve it. I have three child components, each with their own set of input controls that are supposed to feed into a parent component. Howeve ...

Is there a way to keep my navigation bar fixated at the top while scrolling?

I've attempted using class=navbar navbar-default navbar-fixed-top, but it's not working. I believe I may be struggling to find the best position to place the class. Alternatively, is there any JavaScript or jQuery code that could assist with this ...

Divide the table columns and place them into their respective individual tables

I am faced with a task to split a table with multiple columns into separate tables for each column. My approach is as follows: Identify th in each column. Use the th tag as an indicator for a new column. Locate tr td in each column. Create a new table ...

Angular oppositional $watch

Can an inverse use of $watch in Angular be implemented? The Issue I am using angular-translate and I aim to execute a $http.put for every missing translation. However, I encounter the following error: "10 $digest() iterations reached" when ...

Transforming HTML with JavaScript

I am facing a challenge in my JavaScript application where I receive HTML code from an endpoint that contains radio buttons. Unfortunately, I cannot modify the HTML content coming from this endpoint. My goal is to convert these radio buttons into regular b ...

Could someone clarify the code for me? I'm struggling to grasp the meaning behind using !toggle in the onClick function and ? in the return statement

I'm having trouble understanding this code. I don't know why there is !toggle inside onClick and ? inside return. As a beginner, this code is confusing to me. Any help in explaining this code would be greatly appreciated. import {useState} from ...

Remove the 'note' item from a MongoDB collection using Node.js Express

I am contemplating how to remove a 'note' from my mongoDB using Node.js Having recently started exploring Node.js, Express and mongoDB. I will simply share my code here and let it do the talking... notesController.js: app.delete('/api/n ...

What is the best way to showcase information within a node framework?

I am looking to create a family tree using the MVC framework. Furthermore, I need to be able to insert data with relationships. I have object data that I would like to display along with its entities in a node structure. Any assistance on this matter wou ...

Is the installation of the .NET Framework necessary to execute C#/C code using NodeJS?

I am looking to execute C#/C++ code using NodeJS. From my research, it seems like the edgejs library enables running .NET code in JavaScript. So I'm wondering, do I need to have the .NET framework installed on the system hosting the WEBApp through Nod ...