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

Responsive Bar Chart using jQuery Mobile and ChartJS that appears on the screen only after resizing

I have been experimenting with adding a responsive bar chart using Chart.js in one of my JQM projects. Here is what I have accomplished so far: http://jsfiddle.net/mauriciorcruz/1pajh3zb/3/ The Chart needs to be displayed on Page Two and it should be res ...

"Trouble in Transmitting: Node.js Fails to

As a beginner in programming, I am currently following a tutorial to enhance my skills. I've encountered a roadblock and I can't seem to successfully post new entries using the code. I'm struggling to identify what I might be missing here. ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

When trying to submit a form, encountering an `Uncaught ReferenceError` due to calling ajax within

Attempting to trigger an ajax function within a form in order to retrieve a value for the dropdown. mypython.py @app.route('/new_data', methods = ['POST', 'GET']) def new_data(): #Filter data and return the data(data_lis ...

jQuery Slider Showing Incorrect Images

My jQuery slider is acting strangely. It hides the first image, shows the second one, but then just repeats the cycle by showing the first image again instead of loading the third one. I'm puzzled about what could be causing this issue in my code. Do ...

Creating golden phone numbers from a numerical series using JQuery

My latest work assignment involves generating gold numbers from a number series such as 52xxxxxx. Gold numbers could be examples like 52999999, 52727272, or something similar. I'm feeling a bit overwhelmed and unsure of where to begin with this task. ...

The document.write function in JavaScript is malfunctioning

I've been attempting to utilize the javascript function document.write to incorporate an external css file in my template. However, I am aiming to achieve this using Twig, like so: document.write('<link href="{{ asset('bundles/activos/cs ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

How to access and utilize parent directive methods effectively in AngularJS

Looking for advice on the best way to utilize parent directive methods in its child directive. Option one: Pass it as a scope parameter in the HTML where you initialize the child directive. Option two: Make the parent directive required and gain ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...

How can I retrieve the attribute value in a JSP request using jQuery AJAX?

On my website, I have a servlet page and a JSP page. JSP: $.ajax({ url: window.location.href + "?b=b", success:function(data){ //doSomething(data); console.info('$ ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

I'm facing some difficulties in sourcing my header into a component and encountering errors. Can anyone advise me on how to properly outsource my header?

Looking to streamline my headers in my Ionic 4 project by creating a separate reusable component for them. Here's how I set up my dashboard page with the header component: <ion-header> <app-header title="Dashboard"></app-he ...

Create a fresh CSS class using the Chrome developer tool

Can a brand new CSS class be inserted in Chrome dev tools in this way? .myclass { background-color: yellow; } ...

What is the reason for JSHint alerting me about utilizing 'this' in a callback function?

While working in my IDE (Cloud 9), I frequently receive warnings from JSHint alerting me to errors in my code. It is important to me to address these issues promptly, however, there is one warning that has stumped me: $("#component-manager tr:not(.edit-co ...

Smoothly automate horizontal scrolling using JavaScript

My programming journey involved creating a code snippet that automatically scrolls paragraphs horizontally, giving it the appearance of "Breaking News" updates on popular websites. The Javascript script I implemented performs automatic scrolling, but once ...

Unleashing the power of eventListeners through exponential re-rendering upon state updates

Trying to implement an eventListener for "keydown" to update the state (a boolean named showMenu). I placed it inside a useEffect, but it's not functioning correctly and I can't pinpoint the issue. When I include showMenu in the dependency arra ...

Unable to set a JSON data as a value for a JavaScript variable

I am currently developing a YT mp3 downloader using the API provided by youtubeinmp3. I have been successful in obtaining the download link in JSON format. https://i.stack.imgur.com/3mxF2.png To assign the value of "link" from the JSON to a JavaScript va ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...