AngularJS allows you to toggle the visibility of a div at set intervals, creating

I am struggling with the task of showing and hiding a div that serves as an alert for my application.

Currently, I am using $interval to create a continuous show and hide action on the div. However, what I aim for is to have the DIV visible for X amount of time and then hidden for the same X amount of time.

This is how I am currently implementing it:

function showNotification(idNotification) {
       $('[id*=noti_]').addClass('dis_none');
       $('#noti_' + idNotification).removeClass('dis_none');
}

function hideNotification() {
       // $('#noti_' + idNotification).addClass('dis_none');
       $('[id*=noti_]').addClass('dis_none');
}

function checkCalendar() {
       var tomorrow = moment().add(1, "d").format("YYYY-MM-DD");
       WebApiFactory.GetShiftPeriod("BodyShop", "2017-11-07").then(function (data) {
           // WebApiFactory.GetShiftPeriod("BodyShop", tomorrow).then(function (data) {
           if(data[0].TargetPlantValue === 0){
               showNotification("alert");
           }
       });
}

function notifications(type, time) {
       switch (type) {
           case "calendar":
               // checkCalendar();
               $interval(function () {
                   checkCalendar();
                   console.log("Active");
               },time * 1000);
               $interval(function () {
                   hideNotification();
                   console.log("Hide");
               }, time * 1001);


               break;
       }
    }

Any advice or suggestions are greatly appreciated.

Answer №1

Uncertain about your intentions, but if you aim to display a dialog for a set period and then hide it, it is important not to initiate both intervals simultaneously. Instead, wait until the dialog appears and then commence a timer to conceal it.

For instance, if you want to hide the dialog after '100' milliseconds.

function handleNotifications(type, duration) {
     switch (type) {
         case "calendar":
              $interval(function () {
                   checkCalendar();
                   $timeout(hideNotification, 100);
              }, duration * 1000);
         break;
     }
}

Furthermore, note that I utilized a $timeout directive in this scenario. It functions similarly to $interval, but operates only once.

How can I ensure that the time the div is displayed equals the time it is hidden?

It's slightly more complex, so let's implement a different approach. Here, we utilize a single $interval but maintain a current state called isNotificationActive to manage showing/hiding the element based on this state.

Another thing to keep in mind is the utilization of $interval.cancel to halt any previously running intervals, if applicable.

var notificationInterval = null,
    isNotificationActive = false;

function handleNotifications(type, duration) {
     switch (type) {
         case "calendar":
              $interval.cancel(notificationInterval);
              notificationInterval = $interval(updateNotificationState, duration * 1000);
         break;
     }
}

function updateNotificationState() {
     if(isNotificationActive) {
         // Hide the element here
     } else {
         // Show the element here
     }
     isNotificationActive = !isNotificationActive;    
}

Answer №2

I have a suggestion for handling notifications...

One way to manage hiding notifications is by making the notification element(s) responsible for hiding themselves. Here's an example code snippet:

function showNotification(idNotification, hideAfter) {
    var $el = $('#noti_' + idNotification);
    $timeout.cancel($el.data('timoutRef')); // Cancel any scheduled auto-hide
    $el.removeClass('dis_none'); // Display the notification
    if(hideAfter) {
        // Schedule the notification to hide after a specified time
        $el.data('timoutRef', $timeout(function() {
            $el.addClass('dis_none'); // Hide the notification
        }), hideAfter);
    }
}

Make sure to modify checkCalendar() and notifications() accordingly:

function checkCalendar() {
    WebApiFactory.GetShiftPeriod("BodyShop", "2017-11-07").then(function (data) {
        if(data[0].TargetPlantValue === 0) {
            showNotification("alert", 1000/2); // Show immediately, then hide after half a second
        }
    });
}

function notifications(type, time) {
    switch (type) {
        case "calendar":
            $interval(checkCalendar, time * 1000); // Set interval based on total cycle time
        break;
    }
}

If your notifications do not overlap on the screen space, managing their visibility should be straightforward. However, in cases where multiple notifications might compete for the same area, consider reducing them to a single visible notification.

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

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

I'm having an issue with Internet Explorer where the link doesn't function properly when I enclose the content within an <a> tag. Could anyone

I understand that this might not be the preferred approach, but a customer has requested live text wrapped in just one HTML tag.... Here's the challenge I'm facing: I currently have some code structured like this: <a href="google.com"> ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Issue arises when applying both overflow-x:scroll and justify-content:center

Encountering a problem with using overflow-x: scroll and justify-content: center on a flex parent container. Here is my code snippet: The issue: the first flex child item is not visible as it is cropped on the left side. Please refer to the screenshot and ...

Retrieve the identification number from the code snippet containing the "append(<tr><td="ID">..." template

I have a table that I'm populating with data from a firebase database using the append() function. $("#table_body").append("<tr><td>" + name + "</td>" + "<td>" + brand + "</td>" + ...

Using JavaScript (without jQuery), take away the CSS class from an element

Seeking assistance from experts on the process of removing a class from an element solely using JavaScript. Kindly refrain from suggesting solutions involving jQuery as I am unable to utilize it, and have little knowledge about its functionalities. ...

"Having issues with Django not properly applying the JavaScript and CSS files I've linked in

I have completed my project and organized all the necessary files, including index.html, css, js, and settings.py within the appropriate folders. I am encountering an issue with applying a pen from the following source: CodePen index.html <!DOCTYPE h ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

Combining Various Time Periods in JavaScript

After encountering various old solutions, most utilizing jQuery, for adding multiple durations together, I decided to create my own script below. While I may not be a JS expert, I am open to input on any potential issues with this code or a more efficient ...

Navigate to a different state with ui-router upon entering the page

I am implementing two wizard flows, flow A and flow B, each collecting different sets of information. states["wizard"] = { abstract: true, url: "^/wizard", controller: "wizardController", templateUrl: "wizard.html" ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

Using a ForEach iteration to loop through a table in C# and jQuery

My generated table structure is as follows: <div class="row"> <div class="col-md-12"> <div id="calendar"></div> <table id="report" class="table"> <thead> <tr> <th> ...

How can React Native efficiently retrieve data from multiple APIs simultaneously?

In my current project, I am incorporating multiple APIs that are interlinked with each other by sharing the same data structure... Below is the code snippet: export default class App extends React.Component { constructor(props) { super(props); } ...

Decrease in internal width

Seeking assistance to adjust the internal border width for better text alignment. I've been struggling with this issue as a beginner in the web development field and would appreciate some guidance. Link to image Here is a snippet of my HTML code: & ...

Sending data to a PHP file with JQuery Ajax: A step-by-step guide

My goal is to utilize jQuery and ajax to transmit information to a php file. However, I am facing an issue where I can only retrieve the response from ajax in json format and unable to successfully send the data. $.ajax({ url: 'myFile.php' ...

Center-align the text in mui's textfield

What I'm looking for is this: https://i.stack.imgur.com/ny3cy.png Here's what I ended up with: https://i.stack.imgur.com/vh7Lw.png I attempted to apply the style to my input props, but unfortunately, it didn't work. Any suggestions? Than ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

"Crafting a Personalized TabControl Directive in AngularJS: Step-By-

Currently, I am using Zurb Foundation 4 as my CSS/Grid Framework which includes a Tab Control feature. However, when this tab control is placed on a page loaded via ng-view, it malfunctions. To address this issue, I decided to create my own directive sinc ...

Disable the default form input reset button generated by Internet Explorer 10

Just have one field form for search input. Below is the HTML code: <form class = "search-form hide-on-mobile"> <input class = "global" type = "text" placeholder = "Who are you looking for ?"> <but ...

When adjusting to mobile dimensions, the responsive website design struggles to center the navbar properly

I am currently developing my senior year portfolio website and I am struggling to center the navbar (Work About Contact) when it is in mobile mode. My goal is for it to be positioned directly below the logo, perfectly centered, but so far nothing I have tr ...