Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white space appearing above or below the image that is displayed. Below is the code snippet I am using:

HTML

<div class="img-container">
    <img id="img1" src="img/image1.jpg" />
    <img id="img2" src="img/image2.jpg" />
    <img id="img3" src="img/image3.jpg" />
</div>

CSS

.img-container{
    text-align: center;
    visibility: hidden;
    margin-top: 20px;
}

JS

var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var img3 = document.getElementById('img3');

("li:nth-child(2)").on('click', function() {
    img1.style.visibility = 'visible';
    img2.style.visibility = 'hidden';
    img3.style.visibility = 'hidden';
});
("li:nth-child(3)").on('click', function(){
    img2.style.visibility = 'visible';
    img1.style.visibility = 'hidden';
    img3.style.visibility = 'hidden';
});
("li:last-child").on('click', function() {
    img3.style.visibility = 'visible';
    img2.style.visibility = 'hidden';
    img1.style.visibility = 'hidden';
});

Despite experimenting with the display: hidden CSS property along with .toggle(), I haven't been able to resolve the issue of white space around the hidden image. As I am new to JS/jQuery, I would appreciate any guidance on how to tackle this problem effectively. Thank you.

Answer №1

If you want to control the visibility of elements in your HTML page, you can utilize the CSS property display along with values like none and block. The display property determines how an element should be displayed on the screen.

To make an image visible:

img1.style.visibility = 'visible';

You can also achieve the same effect using jQuery:

$("#img1").css("display", "block");

Similarly, to hide an image:

img1.style.visibility = 'hidden';

Or with jQuery:

$("#img1").css("display", "none");

Another tip is to consider using the inline-block value instead of block for list items to improve their layout.

Answer №2

For those seeking a jQuery solution:

var $image1 = $( "#img1" ),
    $image2 = $( "#img2" ),
    $image3 = $( "#img3" );

$( "li:nth-child(2)" ).on( "click", function() {
  $image1.show();
  $image2.hide();
  $image3.hide();
} );
$( "li:nth-child(3)" ).on( "click", function() {
  $image1.hide();
  $image2.show();
  $image3.hide();
} );
$( "li:nth-child(4)" ).on( "click", function() {
  $image1.hide();
  $image2.hide();
  $image3.show();
} );
$( "li:last-child" ).on( "click", function() {
  $image1.show();
  $image2.show();
  $image3.show();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul style="list-style: none;">
<li>Click a button:</li>
<li><button>Show First Picture</button></li>
<li><button>Show Second Picture</button></li>
<li><button>Show Third Picture</button></li>
<li><button>Reset</button></li>
</ul>

<div class="img-container">
  <img id="img1" width="300" height="300" src="https://blognumbers.files.wordpress.com/2010/09/1.jpg" />
  <img id="img2" width="300" height="300" src="https://blognumbers.files.wordpress.com/2010/09/2.jpg" />
  <img id="img3" width="300" height="300" src="https://blognumbers.files.wordpress.com/2010/09/3.jpg" />
</div>

Answer №3

Setting the CSS property visibility to hidden will hide an element while still maintaining its space on the page.

On the other hand, setting the CSS property display to none will hide the element completely without taking up any space on the page.

In most cases, it is more commonly needed to use:

display = 'none';

or

display = ''; // to make it visible

Answer №4

Instead of relying solely on the visibility property, switching to the display property might offer a simpler solution. Another approach could involve streamlining your JavaScript code for easier management. One option is to reveal the corresponding img based on the index of the clicked li.

For example:

$(function() {
  $(".img-controller li").on("click", function() {
    var i = $(this).index();
    $(".img-container img").hide();
    $(".img-container img:eq(" + i + ")").show();
  });
  $(".img-container img").not(":first").hide();
});
.img-controller {
  list-style-type: none;
  padding: 0;
}
.img-controller li {
  display: inline-block;
  background: #eee;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="img-controller">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
<div class="img-container">
  <img src="https://placekitten.com/50/50" />
  <img src="https://placekitten.com/50/40" />
  <img src="https://placekitten.com/50/30" />
</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

Using JavaScript to extract the metadata of an image from a remote location

Is there a way to extract XMP metadata from a JPEG file using JavaScript? I came across a method for doing it in PHP (How can I read XMP data from a JPG with PHP?) which can be adapted for JavaScript using AJAX. However, the issue arises when trying to acc ...

Unable to connect the CSS file from the JSP during a Cross Domain request in Internet Explorer 9

I have created a GWTP web application and am making AJAX calls to a JSP page on a different domain (Cross domain) from the GWT client side. Most of the time, the CSS files are linking correctly and working fine. However, occasionally they do not link prop ...

Can you guide me in utilizing this API endpoint efficiently to enable search functionality using React Query?

const { isLoading, isError, data, error, refetch } = useQuery( "college", async () => { const { result } = await axios( "http://colleges.hipolabs.com/search?name=middle" ); console.log(&quo ...

Interact with the horizontal click and drag scroller to navigate through various sections effortlessly, each designed to assist you

Currently, I am facing an issue with my horizontal scrolling feature in JavaScript. It works perfectly for one specific section that has a particular classname, but it fails to replicate the same effects for other sections that share the same classname. ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

Adjust the body class dynamically based on the URL in AngularJS

Here is the link to my website To Log In - http://localhost/ang/#/login To Access Dashboard - http://localhost/ang/#/dashboard See below for the HTML code for the body tag If the current URL is http://localhost/ang/#/login, then the body should include ...

Challenges with aligning Fontawesome stacks

I utilized the code example from Fontawesome's website to create a pair of stacked social media buttons and enclosed it in a div element to float them to the right side of the page. <div class="social-icons"> <span class="fa-stack fa-lg"> ...

Discover the exclusive Error 404 dynamic routes available only in the production version of NEXT13! Don

Hey everyone, I'm encountering an issue with NEXT's dynamic routing (Next 13). My folder structure looks like this: - user/ -- [id]/ --- page.js It works fine in dev mode but not in production. What am I trying to do? I've created a "page ...

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

IE is notorious for not playing well with CSS

I am facing an issue with my Google search box code. It works perfectly on Firefox, Chrome, and other browsers except for Internet Explorer. Can anyone help me troubleshoot this? Below is the code snippet: Abulkas Tablet #outerContainer{ width: ...

tips for organizing the <div> element horizontally within a design

I have reviewed some similar questions that have been posted and attempted to apply their solutions to my code. However, I am still encountering difficulties. Below is the code that I need help with. I am looking to organize the main content along with t ...

Implementing a function in jQuery to create a "Check All" and "Uncheck All" button

Can someone please guide me on how to implement a check all and uncheck all functionality when I check individual checkboxes one by one? Once all checkboxes are checked, the 'checkall' checkbox should automatically be checked. Below is the code s ...

Ways to designate a tab as active

Having trouble styling the active tab in my tabbed menu created with Bootstrap. The active class seems to only affect the first tab. How can I make it work for all tabs? Check out this screenshot for reference. Below is the code snippet: <script ...

Foundation 5 - ensure background-image covers the entire column width

I'm trying to achieve a unique layout using Zurb Foundation. My goal is to have two columns, each taking up half of the screen: <div class="small-6 columns"><!-- INSERT IMAGE HERE --></div> <div class="small-6 columns"> < ...

A tool developed in Javascript that allows for the conversion of .ini files to .json files directly on the client

Does anyone know of a JavaScript library that can convert .ini files to .json files on the client-side? I checked out this library, but it doesn't meet my requirements. Here is an example of an .ini file: [Master_Settings:1] Model Name=RC-74DL IP Ad ...

Exploring ways to display featured posts within specific category sections

I have 2 featured posts in 1 div id, one with a big class and the other with a small class. I want the big featured div to display posts based on categories. The code for the big featured post is shown below: <div class="main_feat"> ...

What is the best way to display a scrollbar at the bottom of the table while setting the table height to

After writing the css provided below, I noticed that it works fine on my laptop screen. However, when viewing it on a larger monitor, there is empty space at the end of the table. .wrapper{ width:auto; height: 500px; overflow-x: scroll; ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...