Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that when the width is set to 0, instead of disappearing, the links inside the menu get squished to the left. How can I achieve the desired effect of making the links completely disappear when the width is set to 0 and reappear when the width is set to 100vw?

I attempted to use an if statement where, if the width is 0, the links are emptied out, but this approach did not yield the expected outcome.

Any assistance on solving this dilemma would be greatly appreciated.

<div id="menu">
    <div class="menu-item">
        <a href="#section-1" onclick="$('#on-menu').click();">Home</a>
    </div>
    <div class="menu-item">
        <a href="#section-2" onclick="$('#on-menu').click();">Profile</a>
    </div>
    <div class="menu-item">
        <a href="#section-3" onclick="$('#on-menu').click();">Contact</a>
    </div>
</div>

<script>

/*When icon (#on-menu) is clicked, this animates width from 0px to 100vw*/
isLarge = false;

$("#on-menu").click(function(){
    $("#menu").animate({width:(isLarge ? '0px' : '100vw')});
    isLarge = !isLarge;    
});

/*The following attempt to make the links disappear when the width is set to 0 failed*/

if($("#menu").width() == '0px'){
    $( ".menu-item" ).empty();
}

</script>

Answer №1

apply overflow:hidden to conceal the content of the div

Answer №2

Check out this JSFIDDLE example

The default value of the overflow property is "visible". This explains why the text remains visible even when the width is set to 0px. However, if we change the overflow property to "hidden", the text will be hidden when the width is 0px.

Answer №3

To enhance the mark-up, my primary recommendation would be to make some modifications. Embedding an inline element such as a <span></span> within the <a> tag allows you to freely apply styles to the content inside the menu item.

Please note: keep the icon outside of this inner <span>.

Subsequently, establish a rule that initially conceals the inner content of the <span>, and upon clicking, you can either toggle between inline styles or introduce a new class with predefined styles to reveal the content of the <span>.

A similar outcome can be achieved using CSS hover effects by adding a transition to the <span>.

For instance: Adding transition: .7s; to the inner <span>, then adjusting the width when hovering over the parent element, the <a> tag, will result in a smooth slide-out effect. Upon hovering off, it will revert back, emphasizing CSS's capability to handle animations and transitions instead of relying heavily on JavaScript.

Alternatively, consider following these steps:

Copy and paste the following code into your browser's URL bar...

data:text/html,<div id="menu"> <div class="menu-item"> <a href="#section-1" onclick="$('#on-menu').click();">Home</a> </div> <div class="menu-item"> <a href="#section-2" onclick="$('#on-menu').click();">Profile</a> </div> <div class="menu-item"> <a href="#section-3" onclick="$('#on-menu').click();">Contact</a> </div> </div>

Then add and experiment with these styles...

.menu-item a {
    width: 0px;
    display: block;
    overflow: hidden;
}

.menu-item:nth-child(even) {
    background-color: gray;
}

.menu-item:nth-child(odd) {
    background-color: lightgray;
}

Answer №4

To accurately test the width of the element, it is best to do so within the animate callback function and utilize 0 instead of 0px:

    $("#menu").animate({width:(isLarge ? '0px' : '100px')}, function(){
        if( $(this).width() == 0 ) { 
            $( ".menu-item" ).empty();
        }
    });

isLarge = false;
$(".on-menu").click(function(e){
    e.preventDefault();
    $("#menu").animate({width:(isLarge ? '0px' : '100px')}, function(){
        if( $(this).width() == 0 ) {
            $( ".menu-item" ).empty();
        }
    });
    isLarge = !isLarge;    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">
    <div class="menu-item">
        <a href="#section-1" class="on-menu">Home</a>
    </div>
    <div class="menu-item">
        <a href="#section-2" class="on-menu">Profile</a>
    </div>
    <div class="menu-item">
        <a href="#section-3" class="on-menu">Contact</a>
    </div>
</div>

Answer №5

To achieve the desired outcome, simply set overflow:hidden.

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

Converting a JavaScript dictionary into an array of documents: The ultimate guide

I have an object that looks like this: const obj = { "restaurant": 20, "hotel": 40, "travel": 60 } Is there a way to transform it into the format below? const newArray = [ { "category_name": "restaurant", "amount": 20 }, { "category_na ...

Reducing size and Assembling JavaScript and CSS

I find myself in a bit of a dilemma when it comes to using just one JS file and one CSS file for a website. Let me elaborate: As someone who mainly works with CMS platforms like Joomla, I often run into issues during page speed tests where experts recomme ...

Is it possible for me to send my form values using jQuery .load() and have them be interpreted by PHP $_POST?

Is it possible to pass form values using the load() function in jQuery and then access them as $_POST parameters in PHP? ... ...

Using PHP to identify the origin of a JavaScript file on a webpage

I have been attempting to locate an embedded stream link from a certain webpage. After inspecting the source code of the page, I found the following snippet: <script type='text/javascript'> swidth='640', sheight='460';& ...

I am having issues with the Load More Posts Ajax Button on my WordPress site and it is

I'm trying to display more posts when a button is clicked. Upon inspecting and checking the network, everything seems to be working fine, or at least that's what I assume. https://i.sstatic.net/44VS1.jpg https://i.sstatic.net/KEkiz.jpg I&apos ...

Is it required for IDs in CSS to always correspond to a single element? How should IDs be handled if the same element is repeated multiple times on

Is it possible to have a menu that is visible at both the top and bottom of an extensive HTML page using the following code: <div id="menu"><ul><li>Home</li><li>About</li></ul></div> Would it be appropriate ...

Sending data as arguments in URL fetch requests with JavaScript

Hey there, I've been experimenting with making a GET request in React. In the past, with jQuery, I used to do something like this: $.get("Run",{ pr: "takeData", name: "Bob"}, function (o) { console.log(o) ...

New to CSS/Ruby - What causes two adjacent buttons to have varying sizes?

The varying sizes of my search and login buttons located beside each other are puzzling me. Could it be due to the fact that the search button is enclosed within a submit_tag argument while the login button is not? If this is indeed the case, how can I mak ...

Problem Encountered When Using jQuery addClass on Associated Element

In my code, clicking on an 'a.mainSubMenuLinkA' element successfully triggers a page change. After this, I need to apply the 'active' class to the previously clicked 'a.mainSubMenuHeadingLinkA'. <li><a class="mainSub ...

Is there a way to consistently trigger the browser.webRequest.onBeforeRequest event in Mozilla Firefox when it is launched via a link?

Hello knowledgeable individuals. I am unable to solve this issue on my own. Here is the add-on I have created: 1) manifest.json: { "manifest_version": 2, "name": "Example", "version": "1.0", "description": "Example", "permissions": [ "tabs" ...

Automatically create CSS properties for left and top using absolute positioning

When looking at these websites as models: On each of them, I noticed that there is a well-organized column of boxes for every post. I attempted to recreate this using various methods, but couldn't achieve the exact layout on my own website. It seems ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...

Troubleshooting Firefox in Python Selenium: When using driver.execute_script to delete text characters using JQuery, encountering "SecurityError: The operation is insecure" error

Currently working with Selenium 3.141.0 using Python and Firefox 88.0 with geckodriver 0.29.1. In the past, I successfully used the following JavaScript code to remove unwanted characters (like ®) from web pages, as referenced in this answer: driver.exec ...

Unusual body padding found in the mobile design

When visiting on a mobile device and inspecting the elements in Google Chrome, try disabling the style rule overflow-x: hidden from the body element and then resizing the window. You may notice a white vertical stripe (padding) appearing on the right side ...

Guide: Enhancing Query Context within jQuery Instances Spanning Across Iframes

In my current project, I am facing a challenge with using a jQuery instance across iframes. It's been causing me quite a bit of frustration. Here's the situation: I have an existing web application that loads jQuery (which is aliased as $jq) in ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

Connecting a picture to a web address using the <img class> tag

I'm facing a major issue with the "fade script" I added to my portfolio. It's designed to fade between thumbnails using jQuery and CSS, but it relies on 2 img classes that I can't seem to link properly. Basically, I want to link the image g ...

jQuery datatable in MVC displays incorrect checkbox selections due to cache population

When using .datatable in my MVC view to display a table with multiple columns and checkboxes in each row, I encountered an issue with the caching. If I sort the table by a column other than the original one (such as by number), navigate away from the page, ...

creating PHP buttons to update inventory

As a newcomer to AJAX and PHP, I am facing some challenges with an inventory management system built using phpmyadmin and wamp. The registration/login system is functioning well. However, upon user login, a table displaying all inventory items is generated ...