To set the left position of the div to 0px, click outside of

I recently used this code to have a div move from left to right on the screen. Now, my goal is to make the div snap to the leftmost position with a smooth animation whenever someone clicks outside of it.

For a live demonstration, visit:

$('.top-tittle .menu-icon').click(function () {

  var targetValue;

  if ($('.main-menu').css('left') == "0px") {
    targetValue = '-78%';
  } else {
    targetValue = '0px';
  }

  $(".main-menu").animate({
    left: targetValue
  }, 400);


});

Answer №1

$('.header .menu-icon').click(function() {
  var targetValue;

  if ($('.nav-menu').css('left') == "0px") {
    targetValue = '-78%';
  } else {
    targetValue = '0px';
  }

  $(".nav-menu").animate({
    left: targetValue
  }, 400);
});

$(document).on('click', function(e){
  var $target = $(e.target);
  
  //if the element is the menu icon, or is a child of the menu, ignore the click
  if (!$target.is('.menu-icon') && $target.closest('.main-menu').length < 1) {
    //doesn't belong to the icon or the menu, close the menu
    $('.nav-menu').stop().animate({
      left: '-78%'
    }, 400);
  }
});
.header {
  background-color: green;
}

.menu-icon {
  display: inline-block;
  min-width: 32px;
  min-height: 32px;
  background-color: gray;
}

.nav-menu {
  position: absolute;
  top:20px;
  left: -78%;
  display: inline-block;
  min-width: 80%;
  min-height: 120px;
  background-color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
  <div class="menu-icon"></div>
</div>

<div class="nav-menu"><p>Yayy</p></div>

Answer №2

Here is an example of how you can implement this functionality:

$('html').on('click', function(event) {
    var $clickedElement = $(event.target);
    var isIconClicked = ($clickedElement.hasClass('icon') || $clickedElement.closest('.icon').length > 0);
    var isMenuClicked = ($clickedElement.hasClass('menu') || $clickedElement.closest('.menu').length > 0);

    if (!isIconClicked && !isMenuClicked) {
        $(".menu").animate({
            left: '-80%'
         }, 500);
    }
});

In simple terms, the code snippet ensures that when a user clicks anywhere outside the menu or its icon, the menu will slide to the left.

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

Using Twitter Bootstrap to set a minimum number of lines for thumbnail captions

I currently have a carousel on my website created using Bootstrap that displays 4 columns of thumbnails. You can view the carousel here. When navigating to the third page of the carousel, you will notice that the container increases in height to accommodat ...

How to display only a portion of content using UI Bootstrap collapse feature

In my Angular.js application, I currently have a row of buttons that open up new routes to display partial views. Now, I need to modify some of these buttons to trigger a ui.bootstrap Collapse feature with the view inside it. The template code from the ui. ...

Displaying messages in an Angular 2 chatbox from the bottom to the top

As a newcomer to using typescript, I am currently working on an angular 2 project and facing some challenges with creating a chatbox. My goal is to have new messages displayed at the bottom while pushing the old ones up one line at a time, as shown in this ...

Encountering the error "removeAttr is not a valid function" is causing some issues

Currently, I have integrated jquery-1.7.2.min.js into my project. An unexpected TypeError is arising: $("#TextBox1").removeattr is not a function [Break On This Error] $("#TextBox1").removeattr("disabled"); Can anyone shed some light on why this issu ...

Easily accessible button and span located on the right side

One issue I'm facing is that the button and span are not aligned on the same line. Is there a way to resolve this? <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/c ...

attach jQuery extension to several components

After spending hours scouring the internet, I have yet to find a solution to my issue. The problem is that I have developed a plugin for creating a typing effect on any given element, and it works perfectly when applied to a single element. However, when I ...

A pair of div containers with one set to adjust its height automatically and the other to

I have a container with a height set to 100%. Inside, there are two child divs. Is it achievable to achieve the following heights: First div equal to the height of its content Second div equal to the remaining free space in the container ...

jQuery scrolling table

After struggling with this code for the past 48 hours, I'm reaching out for some guidance. Can someone help point me in the right direction? The task at hand is to create a table that functions similarly to a jQuery calendar. Clicking the next button ...

"How to Align Sliding Images in the Center Across Various Web Browsers

I am trying to adjust the sliding image on my webpage's page banner so that it appears in the center instead of floating to the left or right. Here is the HTML code: <ul class"rslides" id="slides"> <li><img src"image/test.jpg">&l ...

How can I expand all primary accordions while keeping secondary accordions collapsed?

I have a main accordion with nested accordions within each item. My goal is to only expand the main level accordions when clicking the button, without opening the nested ones. I want to open all "Groups" accordions while keeping the sub-accordions labeled ...

How can I use Angular 7 to create a background image for a View made up of multiple components?

Here is the HTML code that I am working with: <app-navbar></app-navbar> <router-outlet></router-outlet> My goal is to have an image set as the background for the home view, which consists of two components: navbarComponent and hom ...

"Exploring the possibilities of JSON integration with a jQuery-powered

How can I dynamically add rows to a listview from JSON data retrieved from an API response? results : { _id: 53f8c48ddc1f5f0419f2ed53, bName: 'Microsoft', phone: 35588319, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

What is the best way to align my logo image and search field at the center of the page, similar to the layout of

Struggling with styling this webpage. I aim to have my logo and search bar centered on the page, surrounded by ample space above and below. You can check it out at NE1UP dot com. All I want is a Google-style layout for my page, but I'm facing difficu ...

Obtain the updated cart total for WooCommerce when the 'updated_cart_totals' jQuery event is triggered

Currently, I have implemented the updated_cart_totals jQuery event to monitor updates to my WooCommerce cart. While this setup successfully triggers when the cart is updated, I am also seeking a way to retrieve the updated total for the cart. Below is the ...

In the realm of typesetting, a punctuated line gracefully weaves its way between two

I am trying to create two sentences with a fixed width of 30%, but the first words in my div go to the next line. The class="left" words are not displaying properly, and then my second div "words" gets mixed with the first div. HTML <div class="bg"> ...

Experiencing issues with connecting to jQuery in an external JavaScript file

My jQuery formatting in the HTML file looks like this: <!doctype html> <html lang="en"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script> </head> < ...

Which domain do I need to use: Google or my own, in order to bypass the Access Denied issue in JQuery

I'm currently experiencing a puzzling issue with my website while using Internet Explorer. Despite loading fine in other browsers, I keep encountering a permission denied error within my JQuery code. What's even more perplexing is that this error ...

Text flickering unexpectedly during hover animation in Bootstrap

Encountered a peculiar issue where dark colors flicker during animation. Link to codepen Adding -webkit-backface-visibility: hidden partially resolves the problem, but it also affects font appearance by making it tighter and brighter. This issue is obser ...

Troubleshooting problem with jQuery attribute value assignment

I am currently working with text boxes that store data in local storage upon saving. $(".formFieldUserData").each(function () { var key = $(this).attr("name"); var value = $(this).attr("value"); localStorage.setItem(key, value); } However, I have c ...