Concealing the sidebar navigation menu on the web application

I have developed a custom Angular 4 web application. My goal is to implement an automatic hide feature for the navbar when a user hovers over it. I came across an example that demonstrates what I want to achieve at https://codepen.io/JFarrow/pen/fFrpg. Despite researching documentation and online resources, I am still unable to determine how to accomplish this task. Below is my code from the navmenu.component.html file:

<meta http-equiv="pragma" content="no-cache" />

<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script type="text/javascript" src="jquery-1.8.3.js"></script>

<div class='main-nav'>
    <div class='navbar navbar-inverse'>
        <div class='navbar-header'>
            <a class='navbar-brand' [routerLink]="['/home']">Navbar</a>
            <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
                <span  (click)="isCollapsed = !isCollapsed">Toggle navigation</span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
            </button>
        </div>
        <div class='clearfix'></div>
        <div class='navbar-collapse collapse' >
                <ul class='nav navbar-nav'>
                    <li [routerLinkActive]="['link-active']">
                        <a [routerLink]="['/home']">
                            <span class='glyphicon glyphicon-home'></span> Home
                        </a>
                    </li>
                    <li [routerLinkActive]="['link-active']">
                        <a [routerLink]="['/login']">
                            <span class='glyphicon glyphicon-log-in'></span> Log In
                        </a>
                    </li>
                    <li [routerLinkActive]="['link-active']">
                        <a [routerLink]="['/margin']">
                            <span class='glyphicon glyphicon-list'></span> Report
                        </a>
                    </li>
                    <li [routerLinkActive]="['link-active']">
                        <a [routerLink]="['/smart-table']">
                            <span class='glyphicon glyphicon-list'></span> Smart table
                        </a>
                    </li>
                </ul>
</div>
    </div>
</div>

Moreover, here is my code from the navmenu.component.ts file:

import { Component } from '@angular/core';

@Component({
    selector: 'nav-menu',
    templateUrl: './navmenu.component.html',
    styleUrls: ['./navmenu.component.css']
})
export class NavMenuComponent {
    public isCollapsed: boolean = false;

    public collapsed(event: any): void {
        console.log(event);
    }

    public expanded(event: any): void {
        console.log(event);
    }
}

Lastly, I have included styles in my navmenu.component.css file:

li .glyphicon {
    margin-right: 10px;
}

/* Highlighting rules for nav menu items */
li.link-active a,
li.link-active a:hover,
li.link-active a:focus {
    background-color: #4189C7;
    color: white;
}

/* Keeping the nav menu fixed on top of other elements */
.main-nav {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
}

@media (min-width: 768px) {
    /* Sidebar layout for small screens */
    .main-nav {
        height: 100%;
        width: calc(25% - 20px);
    }
    .navbar {
        border-radius: 0px;
        border-width: 0px;
        height: 100%;
    }
    .navbar-header {
        float: none;
    }
    .navbar-collapse {
        border-top: 1px solid #444;
        padding: 0px;
    }
    .navbar ul {
        float: none;
    }
    .navbar li {
        float: none;
        font-size: 15px;
        margin: 6px;
    }
    .navbar li a {
        padding: 10px 16px;
        border-radius: 4px;
    }
    .navbar a {
        /* Truncating text if too long */
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

I would appreciate guidance on where to implement the necessary code to achieve the desired functionality. Various solutions involving JavaScript functions or Bootstrap features have not been successful for me so far.

Thank you for your assistance.

Answer №1

If you're looking to implement a scroll event listener in your Angular app, there are a few ways to go about it. One approach is to add the listener to a specific component rather than the entire page. For example, if you have separate components for your navbar and content, you could add the listener to the content component like this:

<navbar-component></navbar-component>
<content-component (scroll)="scrollFunction()"></content-component>

Inside the scrollFunction, you can use a debounce and timeout to track when scrolling starts and stops. This will allow you to toggle a variable like isScrolling based on the user's scrolling behavior.

If you prefer adding the scroll listener directly to the document or window object, you can still achieve the desired functionality by toggling classes based on the scroll behavior:

<navbar-component [class.navbar-hidden]="isScrolling"></navbar-component>
<content-component (scroll)="scrollFunction()"></content-component>

In cases where the content-component also includes the navbar, you can utilize HostListener instead of template binding to listen for the scroll event:

@HostListener('scroll') myScrollFunction() {
 ... same code as above ...
}

To make the navbar slide or fade in and out smoothly, consider adding CSS transitions to the navbar-hidden class. Additionally, if you want the navbar to only appear when scrolling back up, you can modify the logic in the scroll function accordingly.

By examining the scroll event data, you can determine whether the user is scrolling up or down and adjust the visibility of the navbar accordingly. Remember to store the last scroll position to compare with the current position for accurate tracking.

Whether you choose the template binding approach or HostListener, passing the $event parameter allows you to access scroll data within the function:

<navbar-component [class.navbar-hidden]="isScrollingDown"></navbar-component>
<content-component (scroll)="scrollFunction($event)"></content-component>

Overall, implementing a scroll event listener in an Angular app offers flexibility in customizing the appearance and behavior of elements based on user interaction.

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

The slider's border-radius is not being maintained as it moves from left to right

We recently implemented a slider on our website, located at . While we added a border-radius to the slider, we noticed that when the images slide, the border-radius is slightly removed... I attempted to contain the parent element with overflow: hidden, bu ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...

Using an iframe with THREE.js and WebGlRenderer can result in the domElement's getBoundingClientRect method returning 0

I encountered an issue with my code: ... renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setSize(WIDTH, HEIGHT); ... controls = new TrackballControls(camera, renderer.domElement); Strange behavior occurs when I r ...

React Href is not functioning as expected in relative paths

Recently, I delved into React apps and managed to create one with a router. Everything was smooth sailing in dev mode until I tried running index.html from the build folder after npm run build. It seems like all the href links are broken. I suspect somethi ...

I am noticing multiple quantities of the same item being added to my shopping

Recently, I encountered a problem with my online shop that seems to be related to the Javascript. The issue arises when I add an item to my shopping cart from this particular page: . Initially, when I click 'Add to Cart,' the item is correctly ad ...

Ways to ensure the child div's border height matches that of the parent div

I am facing an issue with a child div that has padding. When I add a border-right to the child div, how can I make it full height? Below is the code snippet: <div class="parent"> <div class="child"> <h2>Content</h2> </di ...

Repeatedly animate elements using jQuery loops

Whenever I click a button, a fish should appear and randomly move over a container at random positions. However, in my current code, the animation only occurs once and does not repeat continuously. I want to create a generic function that can be used for m ...

Incorporating PHP variables within JavaScript

As a beginner in web development, I am working on creating an application that heavily relies on JavaScript but also includes PHP/MySQL to prevent users from viewing quiz answers by inspecting the page source. The key pages involved in this project are: in ...

Explore registrations by year and month

I am currently working on coding where a record needs to be displayed based on the date (Month, Year), for instance: 12-2022. However, with the current code I have, I am unable to achieve this. Can anyone offer some guidance on what steps I should take? ...

The server unexpectedly crashed while I attempted to log in to input data for validating testing

Experimenting with inputting incorrect data to observe server responses from the database, such as wrong username/password or non-existent usernames. It worked fine for 1 or 2 attempts, but crashed on the third try: Cannot set headers after they are sen ...

What is the best way to cut off multiple lines of text and display the remaining strings at the

Currently, I am working on a project that involves implementing a gallery feature. The challenge lies in displaying file names which can be quite lengthy, and we are restricted to showing only 2 lines of text. While this can be achieved using line clamp an ...

Display the contents of a JSON array in an HTML format

I have designed an exercise that requires me to display the cities corresponding to each department based on a JSON file. Currently, I am able to display the departments in their respective selections, but I am struggling to only show the cities that corre ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

How can EJS variables be utilized within HTML input fields?

I am facing an issue while trying to use a checkbox to redirect selected users to a new page. I am looking for a solution on how this can be achieved, especially when using mongodb to store the information. Below is my current code snippet: Firstly, I ren ...

Modifying the default classes utilized in React-Bootstrap components: A guide

When using react-boostrap, the default behavior is to include the classes card-title and h5 in a <Card.Title> Foo </Card.Title> tag. Is there a way to change or substitute the h5 element, for example with h4? ...

Creating interactive forms (the optimal method)

My project involves creating an Android Tablet application that will connect to a web service to retrieve dynamic forms which can be filled offline and then submitted when online. These forms are not predefined, and may contain attached images. However, I ...

jPages fails to recognize dynamically added images using jQuery in real-time

I have a HTML and JS script that is designed to load images from PHP using AJAX and then place them into a div. Afterwards, a JavaScript function will paginate the images. Everything works perfectly fine when I hardcode the images manually. However, when I ...

How can I create a full screen button in WebGL with HTML and JavaScript?

How can I create a WebGL full screen button using HTML and JavaScript? I've done multiple searches on this topic but couldn't find a suitable solution. However, I did manage to find a button that works for putting my page in full screen mode. &l ...

Ways to create space between columns in a table

How can I achieve the table layout with a gap between columns, as shown in the design? Initially, I tried using border-collapse: separate but found it difficult to adjust borders in the tbody. So, I switched to collapse. Is this the right approach for crea ...