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

Refresh the table data dynamically without the need for page reloading

Looking for a way to update data in a table without refreshing the entire page? Check out this example: Here is the form: https://i.stack.imgur.com/ISQbC.png After clicking on Update All, only the first row gets updated, not the subsequent rows. <?ph ...

What's the process for changing this arrow function into a regular function?

Hello from a child component in Vue.js. I am facing an issue while trying to pass data from the parent via sensorData. The problem lies in the fact that the arrow function used for data below is causing the binding not to occur as expected. Can anyone gu ...

Getting a jquery lightbox up and running

After experimenting with three different jquery plugins in an attempt to create a lightbox that appears when clicking on a link containing an image, I am currently testing out this one: . Despite adding the plugin source in the head and ensuring that the l ...

Trouble with setting the color attribute using setProperty in a GXT text area

Help needed in dynamically changing the font color of a text area from the color menu. Existing attempts to change it have not been successful. Can someone provide assistance? final ColorMenu fontColorMenu = new ColorMenu(); fontColorMenu.getPalette().a ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

Adding a dynamic form to each row in a table: A step-by-step guide

Hey there! I'm facing a challenge with dynamically generated rows in a form. I want to send only the inputs from the selected row when a checkbox is clicked. Can you help me figure this out? I tried using let rowForm = $(event.currentTarget).closest( ...

What is the process for setting up redux in _app.tsx?

Each time I compile my application, I encounter the following error message: /!\ You are using legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). Although my application functions correctly, I am unsure ...

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...

Looking to center the numbers in my ordered list within a border box - any tips on how to achieve this?

I'm attempting to create a numbered order list with a circular border around it. The goal is to have the number of the list item centered within the circular border and the entire circle centered within the paragraph. Currently, both the number and th ...

Tips for successfully passing multiple data IDs in a Bootstrap modal

Greetings! I am currently facing a challenge with passing multiple data IDs into a bootstrap modal. When I manually assign the data IDs, everything works perfectly: <a id="testB" href="#my_modal2" data-toggle="modal" data-book-id='{"id":10,"name ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

Trouble arises when adding HTML elements to a Content Editable Div. Any text inputted after programmatically inserting HTML content will merge with the last HTML tag instead

I am currently working on a project that involves creating message templates within an app. Users have the ability to add placeholders for fields like names to these templates by clicking a button. They can also remove these placeholders by selecting an &a ...

Angular failing to reflect changes in my select element according to the model

One issue I'm facing in my application is with grouped select elements that share the same options. Whenever one select element changes, it checks the others to see if the new option selected has already been chosen in any of the other selects. In suc ...

Utilizing MDX Component Properties in NextJS

Currently, I am in the process of developing a layout system for my upcoming app inspired by Adam Wathan's approach and his tailwind website. While I have successfully implemented it for js files, I am facing issues trying to apply the same syntax to ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...

Managing PHP AJAX POST requests and storing data in a database

I have tested my PHP code by directly submitting a form without AJAX and it successfully writes the content into the database. However, when I try to do the same with AJAX, it doesn't work. Although the data appears to be transferred to my PHP file a ...

Accessing JSON data from a URL for use within a specific context

I am currently utilizing the request module within Express to fetch a JSON file from a specified link. var url = 'https://api.github.com/users/google/repos'; request.get({ url: url, json: true, headers: {'User-Agent': &apo ...

When transitioning between single-page Angular applications using Protractor, a "JavaScript error: document unloaded while waiting for result" may be encountered

I came across this article discussing the issue of a Javascript error related to a document being unloaded while waiting for a result: JavascriptError: javascript error: document unloaded while waiting for result Although the solution provided seems to wo ...