What is the best way to toggle the visibility of a div using a button? And how can you incorporate a visual effect on the button when

I'm trying to implement a button that can hide and show a div, but for some reason, it only shows the div and doesn't hide it when clicked.

Check out my fiddle:

http://jsfiddle.net/4vaxE/24/

This is my code:

<div class="buttons" style="background-color: rgba(0,0,0,.8);">
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>

<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>

CSS

.button {
    cursor:pointer;
    display:inline-block;
    margin:10px;
    clip: rect(auto,auto,auto,auto);
}

#div1 {
    background:aqua;
    padding:20px;
    width:100px;
    text-align:center;
    display:none;
}
#div2 {
    background:blue;
    padding:20px;
    width:100px;
    text-align:center;
    display:none;
}
#div3 {
    background:orange;
    padding:20px;
    width:100px;
    text-align:center;
    display:none;
}

#div4 {
    background:green;
    padding:20px;
    width:100px;
    text-align:center;
    display:none;
}
a {
    color:aqua;
    -webkit-filter: grayscale(1.0);
}
a:hover {
    color:red;
    -webkit-filter: grayscale(0.0);
}

Javascript

$('#showdiv1').click(function () {
    $('div[id^=div]').hide();
    $('#div1').show();
});
$('#showdiv2').click(function () {
    $('div[id^=div]').hide();
    $('#div2').show();
});

$('#showdiv3').click(function () {
    $('div[id^=div]').hide();
    $('#div3').show();
});

$('#showdiv4').click(function () {
    $('div[id^=div]').hide();
    $('#div4').show();
});

I also want to add a special effect when revealing the hidden div, similar to the "explode" effect shown in this example.

How do I incorporate this effect into my fiddle?

Thanks!

Answer №1

$('#div1').toggle();

To add a toggle effect, consider using slidetoggle or fade instead of show and hide.

Answer №2

JavaScript Animation Code

var selectedEffect="explode";
var options = { percent: 100 };
$('#showdiv1').click(function () {
    $('div[id^=div]').hide();

    $('#div1').show( selectedEffect, options, 500, callback );
});
$('#showdiv2').click(function () {
    $('div[id^=div]').hide();
    $('#div2').show( selectedEffect, options, 500, callback );
});

$('#showdiv3').click(function () {
    $('div[id^=div]').hide();
    $('#div3').show( selectedEffect, options, 500, callback );
});

$('#showdiv4').click(function () {
    $('div[id^=div]').hide();
    $('#div4').show( selectedEffect, options, 500, callback );
});

function callback() {
      setTimeout(function() {
        $( "#effect:visible" ).removeAttr( "style" ).fadeOut();
      }, 1000 );
    };

Check out the updated JSFiddle demo here

Answer №3

$('.showDiv').click(function () {
    $('div[id^=div]').slideUp();
    let divId = $(this).attr('id').substring($(this).attr('id').length - 1);
    $('#div' + divId).slideDown();
});

Check out the live Demo:

http://jsfiddle.net/45k6g/

Answer №4

Here is a suggestion you can experiment with:

When the element with ID "showdiv1" is clicked, consider implementing this function:

if ( $('div[id^=div]').css('display') === 'block' ) {
    $('div[id^=div]').hide();
} else {
    $('#div1').show();
}

Answer №5

$('#showdiv1').click(function () {
    $('div[id^=div]').fadeOut(500);
    $('#div1').fadeIn(1000);
});
$('#showdiv2').click(function () {
   $('div[id^=div]').fadeOut(500);
    $('#div2').fadeIn(1000);
});

$('#showdiv3').click(function () {
   $('div[id^=div]').fadeOut(500);
    $('#div3').fadeIn(1000);
});

$('#showdiv4').click(function () {
    $('div[id^=div]').fadeOut(500);
    $('#div4').fadeIn(1000);
});

Answer №6

Make the switch

 $('div[id^=div]').hide();
    $('#div1').show();

with this new code block

  if($('#div1').css('display')=='none'){
     $('#div1').show();
    }else {
    $('#div1').hide();
    }

Answer №7

Not having much experience with jquery Explode, I decided to consult the documentation to understand it better: http://api.jqueryui.com/explode-effect/. After a brief study of the information provided, I dived into your fiddle.

Upon reviewing the fiddle, a few things caught my attention. Firstly, you needed to include a reference to jquery UI. You can find it here:

To add this in the fiddle, navigate to external resources and input the URL. Once this step is completed, select the box you wish to explode by incorporating the following code:

$('#showdiv1').click(function () {
$('div[id^=div]').hide();
$( "#div1" ).toggle( "explode" ); });

I tested the code and successfully executed the exploding effect. Best of luck to you as you continue experimenting. You were very close to achieving the desired outcome!

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

jQuery - restrict input field based on the value of a different selected field

Could anyone recommend a jQuery plugin that can achieve the following functionality? For example: <label><input type="checkbox" depends_on="foo=5" name="boo" ... /> Check </label> <select name="foo" ... > <option value="5" se ...

Paste a data point from an Excel spreadsheet into a JavaScript script

I'm encountering a major challenge. Currently, I am creating a login process for a client and here is the approach I have taken: function Jump(pal){ if (pal=='10528'){window.open('http://www.google.es','_parent')} Subs ...

How to implement a link_to tag in autocomplete feature with Rails

I'm having trouble adding a link to the show page in autocomplete results. Although my jQuery alert box is working fine, I can't seem to apply CSS to a div using jQuery. Here's the code snippet I've posted below: //application.js ...

Passing request parameters through an HTML form in Spring MVC

Currently diving into Spring MVC and exploring web development. Here is a method from my Controller: @GetMapping("/deleteCar") public String deleteCar(@RequestParam("carId") int carid) { carService.deleteCar(carid); return "redirect:/car/cars"; } ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

Are there any other CSS properties that can achieve the same functionality as "contain: content;"?

Searching for an alternative to the contain: content; CSS property that is compatible with older browsers. Is there a solution out there? Perhaps a CSS hack or workaround? ...

Choose either immediate offspring or immediate offspring of immediate offspring

I am struggling to create a CSS Selector that follows DRY principles. The selector needs to target elements within a group but not those within a subgroup of the main group. Elements should only be direct children of the main group or wrapped in an addit ...

Learn the process of covering the entire screen with a video

I'm attempting to achieve this: IMG Below is the code snippet I've been using: <div class="container" id="containervideo"> <div id="video"> <div class="box iframe-box"> <div class="container"> ...

Incorporating Ajax to allow users to choose an option from a selection for

I want to populate a dropdown menu with values received from an ajax call in the form of a json array. However, the current code results in an empty select element being created. $.ajax({ type: "GET", url: "/wp-content/gta/search_airport.php", data: ...

Images in assets folder are not showing up in Vue Bootstrap

I'm attempting to showcase an image similar to the example provided in this guide Below is the code I am using: <template> <b-container fluid class="p-4 bg-dark"> <b-row> <b-col> <b-img rounded="ci ...

How can CSS be used to print multiple pages without any margins? And what is causing this slight extra height in the output

Check out the Live Demo here, apologies for the messy CSS as I have been experimenting with different styles. I am currently attempting to print PDF files using the browser's print dialog. Each file consists of 4 pages in the DIN lang format with an ...

angular use ngFor directive to restrict the number of rows displayed in a table

In my angular 6 project, I am trying to limit the display to just five rows in a table using ngFor. My current code snippet is as follows: <tbody> <tr *ngFor="let item of routines; let i = index"> <td style="display: none"> ...

The jQuery preloader remains stuck, failing to transition to the main page

I'm struggling to figure out where the problem lies as there are no errors in the console. The page is stuck on the loading screen and won't redirect to the actual site. Here's the HTML code for the preloader: <!--preloader--> &l ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...

The jquery live click event is not functioning properly on iPad devices

I am experiencing an issue with a webpage that has the following code to bind click events <script type="text/javascript"> $(".groupLbl").live("click", function(e) { var $target = $(e.currentTarget); ..... $.getJSON("/somelink.js ...

Insert a horizontal line within the text

I am struggling to get the horizontal lines to work on my traffic light dashboard view for one of my website pages. Despite making multiple adjustments, it seems like I just can't get them to display correctly. Here is an example of what I want: View ...

The ongoing calculation consistently yields a result of zero

This content belongs to the index.php file if(isset($_POST['submit'])) { echo header('Location:answer.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

PHP code $this->item->link within an anchor tag is not functioning properly and is displaying JObject->link instead

Hey, can you help with this quick question? It's driving me crazy! I have a PHP file where I'm pulling in different items like contact details. One of these items is $this->item->link, which displays a perfect URL. All I want to do is make ...

Tips for parsing information contained in a cdata tag using python

I have successfully used Beautiful Soup to extract CDATA from an HTML page, but now I need to parse the contents and save them in a CSV file. Here is the code I am using: from bs4 import BeautifulSoup from urllib.request import urlopen import re import c ...

With the power of jQuery, easily target and retrieve all label elements within a specified

Currently, I'm working on developing a function that should be executed whenever any of the labels for a particular group of radio buttons are clicked. So, I need a way to reference all the labels in this radio button group. In my search for a soluti ...