Easily switch between visible and hidden content by clicking on an image that functions as a swap or toggle

Hey there, I'm new to this and could really use your assistance,

I'm looking for a simple show/hide toggle feature when clicking on an image, where it switches between a 'side arrow' and a 'down arrow' (similar to a dropdown). The goal is to show/hide different text divs. However, I need to utilize classes instead of IDs due to integrating with .NET.

The current setup works with IDs, but I specifically require it to work with classes...

This is the function I have in place:-

<script type="text/javascript">
$(function(){
  $('.nav-toggle').on('click', function(){
    var t = $(this);
    var imgSrc = t.attr('src');
    var divId = t.attr('id');
    $(divId).slideToggle('slow', function() {
      if (imgSrc === '_includes/img/components/toggle_icon_show.png') {
        t.attr({'src' :'_includes/img/components/toggle_icon.png'});
      } else {
        t.attr({'src' :'_includes/img/components/toggle_icon_show.png'});
      }
     });
  });
});
</script>


HTML:-

<img src="_includes/img/components/toggle_icon.png" id="#1" class="nav-toggle">

<div id="1" style="display:none">
<p>Maecenas vulputate, augue vitae sagittis molestie, ipsum neque rhoncus turpis, sit amet iaculis sapien quam sed nunc. Donec neque erat, pulvinar non ultrices sit amet, dignissim at lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi in erat sapien. Nullam mi dolor, consectetur et turpis sit am.</p></div>

Appreciate your help!

Answer №1

My approach involves using a trigger element that toggles the visibility of the next container when clicked.

The trigger element has a class that reflects the state of the following container (open or closed). Upon initialization, the script checks whether the trigger indicates that the next element should be visible and applies the appropriate class to toggle its visibility:

Feel free to experiment with this functionality on this JSFiddle link

JavaScript

jQuery(document).ready(function() {

    jQuery('.toggle-next').each(function(index) {
        var nextEl = jQuery(this).next();

        if(nextEl.is(':visible') ) {
            jQuery(this).addClass('open');
        }
        else {
            jQuery(this).removeClass('open');
        }
    });

    jQuery('.toggle-next').on('click', function(event){
        var nextEl = jQuery(this).next();

        nextEl.toggle('fast', function() {

            if(jQuery(this).is(':visible') ) {
                jQuery(this).prev().addClass('open');
            }
            else {
                jQuery(this).prev().removeClass('open');
            }

        });
    });
}); // jQuery ready

HTML

    <p class="toggle-next">Toogle next content</p>

    <div class="hide">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
      <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

Basic CSS

.hide {
    display:none;
}
.toggle-next {
    color:#000;
    cursor:pointer;
}
.toggle-next.open{
    color:#0f0;
}

While my solution differs from yours, it offers a cleaner and more reusable approach. By utilizing CSS classes for styling, you can easily customize the appearance of both the default .toggle-next state and .toggle-next.open.

Although not flawless, once implemented, this system eliminates the need to worry about the initial state of the "toggleable" element and its trigger or their respective identifiers.

Answer №2

http://example.com/jsfiddle-link

<ul>
    <li>
<div class="toggle_head togglebackground">
    &nbsp;<img src="images/expand.png" alt="Expand" title="Expand" class="expand">
    &nbsp;<img src="images/collapse.png" alt="Collapse" title="Collapse" class="collapse">
    <label> Cookies</label>
</div>
<div class="box toggle_body">
    <ul class="list">
        <li>
           <label disabled="disabled">Information about cookies.....</label>
        </li>
    </ul>
</div>
<!-- !END section (Cookies) -->
</li>
<li>
<div class="toggle_head togglebackground">
    &nbsp;<img src="images/expand.png" alt="Expand"  class="expand">
    &nbsp;<img src="images/collapse.png" alt="Collapse"  class="collapse">
    <label> Terms</label>
</div>
<div class="box toggle_body">
    <ul class="list">
        <li>
           <label disabled="disabled">Information about terms and conditions.....</label>
        </li>
    </ul>
</div>
<!-- !END section (Terms) -->

</li>
</ul>

$(".toggle_body").hide();
$(".collapse").hide();

$(".toggle_head").click(function() {

var $this = $(this);

$this.next(".toggle_body").slideToggle(300, function() {
  $this.children('img').toggle();
});

});

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

When it comes to the CSS `:visited` pseudo-class, I have

I'm having trouble changing the color of the anchor tag and blurring the image after visiting the link. Despite my CSS code, only the color is changing and the image remains unchanged. Here's my CSS code: <style> .image123{ paddin ...

The behavior of Bootstrap 5 containers varies depending on whether they are located within a row

Have you noticed the difference in maximum width between Bootstrap 4.6 and Bootstrap 5? It seems that containers have a 1320px max-width in Bootstrap 4.6, whether inside or outside a row. However, this is not the case in Bootstrap 5 and I couldn't fin ...

Verify whether the combobox has been chosen

Currently, I am dealing with two comboboxes and need to determine which one is selected. My intention is to achieve this using ajax and jquery within a JSP file. if(combobox1 is selected) { perform action 1 } if(combobox2 is selected) { perform actio ...

Activate the search function once the user has finished entering text

Currently facing the following issue: Within my JavaScript file, I have the below code snippet, termChange(evt) { this.rows = []; this.searchTerm = evt.target.value; this.getCases(); } This section of code clears out the ...

Encountering a TypeError in Next.js: "Unable to redefine property: $$id" -

Currently, I am immersed in a Next.js tutorial while following a YouTube guide. The project involves creating a mimic of Facebook Threads to enhance my understanding of Next.js. However, when attempting to create a thread (or a simple post), the applicatio ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...

Update the HTML page when switching between tabs

Currently, I am experiencing an issue with tab navigation in HTML. Within my code, I have two tabs named #tab1 and #tab2, each containing a form. The problem arises when I input data into #tab1, switch to #tab2, and then return to #tab1 - the information I ...

Attaching events to the window in Vue.js

Having recently started working with Vue.js, I have come across a problem related to attaching and detaching keyboard events to the window within one of my components. Below are the methods I am using: created() { this.initHotkeys(); }, beforeDestroy() ...

What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

Is there a way to link the datepicker of one calendar to automatically sync with another under specific circumstances?

I have implemented two datepicker fields on a single page: Start Date and End Date. $("#orders-start-date").datepicker({ dateFormat: "yy-mm-dd", maxDate: new Date(), onSelect: function(date, el) { $this.trigger("orders:filter", date, $ ...

Is there a way to convert the structure of HTML/CSS into JSON format?

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .collapsible { background-color: #004c97; color: white; cursor: pointer; padding: 18px; width: 100%; border: none; text ...

Hold off on continuing the script until the AJAX response has been received

In my script, I have two AJAX calls. The first one checks if a record exists in a database and should stop the script if it does. The second call submits a job. However, I am facing an issue where the job is being submitted before the first AJAX call retu ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

Data sent through AJAX messaging is not being acknowledged

I recently made an AJAX request and set it up like this: $.ajax({ data : { id : 25 }, dataType : 'json', contentType : 'application/json; charset=utf-8', type : 'POST', // the rest of the ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...

How to connect an external module to NuxtJS using Vue.js

Attempting to incorporate a widget/plugin/extension system into my existing web UI built with NuxtJS. Within the pages/view.vue single-file component, I aim to establish the extension system by dynamically loading components indicated through query paramet ...

What is the process for specifying the content type as application/json in an Ajax request?

Do you have a smart contract named GovtContract that functions properly when utilizing curl commands? $curl -X POST -H "Content-Type: application/json" localhost:3000/govtcontract/set -d '{"value":"5"}' | jq $curl -X GET -H ...

"Enable a smooth transition and switch the visibility of a div element when clicked

How to create a dropdown form with a transition effect that triggers on click of an element? Once triggered, the transition works smoothly but clicking again only hides the div element without triggering the transition. See the demo here: Check out the fu ...

What is the best way to position an SVG background image at the bottom of a container?

I am facing an issue with using an SVG as a background-image on a pseudo element. The image is not as tall as the container, so I would like to position it at the bottom of the container while having the background color fill up the top portion to create a ...