The function provided to jQuery's one() method will only be executed the first time the event is triggered

Greetings from a newbie in the world of javascript!

I am currently experimenting with creating custom menu transitions using some basic jquery code.

The concept is to have a menu that is visible initially, and when the user clicks "close," the menu will slide off to the left and wait there. When the user clicks "open," the menu will slide back into its original position.

Unfortunately, it seems to work only for the first click and not thereafter. I would greatly appreciate it if someone could provide a brief explanation as to why this is happening, as I am eager to learn.

Here is my HTML code:


                 <div class="menubar" id="side">

                  </div>

                  <span class="menu close" id="close"></span>
                  <span class="menu open" id="open"></span>

And here is my CSS:


        .menubar
        {
            position:absolute;
            left:0;
            top:0;
            z-index:9;
            height:100%;
            width:350px;
            background:blue;
            display:block;
        }

        .menu
        {
            position:absolute;
            left:360px;
            top:15px;
            z-index:9;
            width:50px;
            height:50px;
            display:block;
            opacity:1 !important;
            cursor:pointer;
        }

        .close
        {
            background:red;
        }

        .open
        {

            left:10px;
            display:none;
            background:green;
        }

And this is my Javascript:


        var $ = jQuery;

            $("#close").one("click", function() {
            $(".menubar").animate({left: "-350px"}, 300, function (){
              });
            $(this).css("display", "none");
            $("#open").css("display","block");
        });


            $("#open").one("click", function() {
            $(".menubar").animate({left: "0px"}, 300, function (){
              });
            $(this).css("display", "none");
            $("#close").fadeIn(300);
        });

Check out my jsFiddle example here.

Thank you for your help!

Answer №1

When using the .one() method in jQuery, keep in mind that the function passed to it will only be executed once per element for each event type. It is recommended to use .on() instead:

var $ = jQuery;

$("#close").on("click", function() {
    $(".menubar").animate({left: "-350px"}, 300, function () {
    });
    $(this).css("display", "none");
    $("#open").css("display", "block")
});


$("#open").on("click", function() {
    $(".menubar").animate({left: "0px"}, 300, function () {
    });
    $(this).css("display", "none")
    $("#close").fadeIn(300)
});

Answer №2

To rectify the issue, replace .one() with .on() within your JavaScript code.

Answer №3

try this approach instead:

$(document).on('click', '#id', function() {
    // do something here
});

This will ensure the event handler is attached even if #id is dynamically added to the DOM.

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

Tips for inserting an AJAX response into the corresponding list item:

When the page loads, I am attempting to send an ajax request that will fetch data for each li element by extracting the href link inside them using the jQuery each() method to generate a dynamic URL for the ajax request. Although I am able to retrieve dat ...

ngOptions compare by actual value

My webserver (node.js) serves a JSON file with a list of languages in the format: { "en" : "English", "fr" : "French" } and a separate JSON settings dictionary like this: { "currentLanguage" : "en" }. The select statement is as follows: <select ng-opti ...

Uninitialized post value preventing AJAX from setting $_POST variable

I'm encountering an issue with sending a JSON object to a .php file. The problem lies in the fact that my POST value doesn't seem to be making its way into PHP's $_POST array. Below is the code snippet causing me troubles: jQuery: $("#subm ...

Table blur function in JavaScript

Encountering an issue with the blur event triggering multiple times instead of just once. Below is the code snippet: function EditMode() { if (!edit) { $('.editable').attr('contenteditable', 'true'); HtmlEdit(); ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

"Is it possible to apply CSS to all HTML elements except for a

I am looking to apply the specified styles to all elements except for a particular class and its descendants. html * { box-shadow: none !important; border: none !important; color: white; } I attempted the following but it did not work as intended: ht ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

Turn off and then reinstall Image when clicked

function show(){ alert("i am pixel"); } function disableImgClick(){ $(".Dicon").unbind('click'); } $(document).ready(function(){ $("#turnoff_btn").click(function (e){ e.preventDefault(); disableImgClick(); }); }); i have a group of ima ...

Determine the outcome of the assessment quiz

Greetings everyone, I apologize for my poor English. I've been searching through numerous documents, but due to my language barrier, I am having trouble understanding them. I have designed a quiz page, but I'm facing an issue where I can't d ...

By utilizing jQuery, I am orchestrating the movement of a series of div elements within a container with the simple click of a button

A group of div elements located within a container. When the button is clicked, the train should start moving. <script> $('document').ready(function(){ $("button").click(function(){ $("#train").animate({left: "300px"}, 2000); ...

The JavaScript array created from parsing JSON returns a value of undefined

Once again, the gecko scenario! The JSON used in this script to fill a listbox has been validated by JSONLint. The code snippet below demonstrates how the parsed data is placed in arrays: pdata = jQuery.parseJSON(data); ctype = pdata[0]; stype = pdata[1]; ...

Positioning a button on the side of the screen while a hidden side panel is open

I am attempting to create an animation using a side panel that will slide into view when a button is clicked. Here is how it appears when the page loads: https://i.sstatic.net/JPQ2W.jpg When the user clicks on one of the buttons, the notes panel will be ...

Content within the p tag is failing to wrap onto separate lines

Take a look at the image below: Here is the code causing issues: <div class="excerpt"> <p>Manual for downloading and installing digital content from the Educational Canaima Project, comprised of learning resources that aim to promote interac ...

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

Prevent clicking on the <div> element for a duration of 200 milliseconds

I need to make this box move up and down, but prevent users from clicking it rapidly multiple times to watch it go up and down too quickly. How can I add a 200 millisecond delay on the click or disable clicking for that duration? View the jsfiddle example ...

Various relationships in Sails.js

Exploring associations in Sails.js beta (version 0.10.0-rc4) has been quite intriguing for me. My current challenge involves linking multiple databases to produce a unified result (utilizing sails-mysql). The association scheme I'm working with invo ...

What is preventing me from accessing session data using nuxtServerInit?

When attempting to retrieve sessions, I encounter an issue. Is everything set up correctly in the following main files: server, config? store/index.js export const actions = { nuxtServerInit ({ commit }, { req }) { console.log(req); } The console log ...

Execute a batch operation or transaction within a Cloud Firestore onCreate trigger

Imagine a scenario where I have a collection of vendor documents in firestore: vendors : { vendor1: { id: "vendor1", name: "John", shopId: "shop1" }, vendor2: { id: "vendor2", name: "Mary", shopId: "shop2" } } Additionally ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Using the <li> element as the primary container for a series of <li>'s within a <ul> is

For my form requirement, I am utilizing Jotforms. After downloading the code, I am currently in the process of customizing the CSS and HTML to fulfill my design needs. Jotforms uses a set of ul , li for managing its HTML structure. However, I encountered ...