What causes the changes made by a form button to the page DOM to be automatically reverted after some time?

Is it possible to swap two HTML DOM nodes?

Let's consider the HTML list below along with a "swap" button:

    <ul class="center-text">
        <li>0</li>
        <li>1</li>
        <li>2</li>
    </ul>

    <form class="center-text">
        <button id="swapButton">Swap</button>
    </form>

Below is the corresponding JS code:

// using the "ready" method as the only jQuery method in this code
$(document).ready(function(){
    document.getElementById("swapButton").onclick = function() {
        var ul = document.getElementsByTagName("ul")[0];

        // pseudo-swap: inserting "child2" before "child0"
        // (indexes are 1 and 5 due to TextNodes between list nodes)
        ul.insertBefore(ul.childNodes.item(5), ul.childNodes.item(1));                      
    }
});

Upon clicking the swap button, the items appear to be swapped initially. However, after a short delay (approximately 1/4 of a second), they revert back to their original positions automatically. The question remains: Why does this happen?

Note: The objective here is purely educational, seeking an understanding of the underlying processes without suggesting alternative jQuery methods.

Answer №1

$(document).ready(function(){
    document.getElementById("swapButton").onclick = function(e) {
        e.preventDefault();
        var ul = document.getElementsByTagName("ul")[0];
        ul.insertBefore(ul.childNodes.item(5), ul.childNodes.item(1));                      
    }
});

The reason for this code is to prevent the button from redirecting the page to itself and undoing all changes made. It's important to stop the default behavior of the button in order to maintain control.

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

Display a window.confirm alert to prevent any unauthorized changes to the URL

Looking to implement a feature that prevents changing the URL from my component. The goal is to display a message and allow users to choose between canceling (no change to URL) or confirming (change the URL). How can I achieve this in the upcoming 13.4 ver ...

Populate modal form with database information without using Bootstrap

As I work on populating a form with data from an sqlite database, I've come across a stumbling block. My code is available for reference on JSFiddle: https://jsfiddle.net/daikini/e71mvg7n/ One important note: Bootstrap isn't being utilized in t ...

What is the best approach for inserting multiple files into MongoDB with just one JavaScript, Node JS, Shell Script, or mongofile CLI script?

Looking for a way to transfer HTML files from a directory to MongoDB using pure JavaScript, NodeJs, shell script, or mongofile CLI. Any assistance would be greatly appreciated. Thank you in advance. ...

Modify appearance of text depending on input (HTML & JS)

I am currently working on building an HTML table using Django. My goal is to dynamically change the color of numbers in the table to red when they are negative and green when they are positive. I understand that JavaScript is required for this functionalit ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

Make sure the time input type uses the 24-hour format, regardless of the system's location settings

Currently, I'm developing a small Angular application and utilizing the following HTML element specifically for setting start hours: <input type="time"> I've observed that this particular element adjusts its format to either 12-hour o ...

Utilizing Node.js and ExpressJS with the integration of external JavaScript files for enhanced functionality

Currently learning NodeJS and working on a basic "class" file that I have saved in an external JS file. How can I make this file accessible for all my routing files and other external JS files that I want to load? /classes/music/usermanager.js function U ...

Incorporate the use of OpenLayers into a Vue.js application

Can anyone share their insights on incorporating Openlayers into a Vuejs project? I'm looking to showcase various layers within my Vue app. Thanks in advance! ...

What is the process for embedding a section of content from a different webpage into a separate division on my website?

Is there a way to pull content from one webpage and display it on another? Would using an Iframe be the best solution for this task? Thank you in advance for your assistance! ...

Swapping out a unique item found in two different arrays

Having 2 arrays: var alleditvals= {username: "twooooo", password: "two_p", address: "two_add"}; var a= {username: "two", password: "two_p", address: "two_add"}; My goal is to replace only the difference ("twoooo") into the object a, making it similar to ...

Utilizing ref passing through props in React to avoid redundancy of frequently employed features

Currently, I have 5 different button components each with unique styles and required props for rendering. However, I want all these buttons to lose focus after being clicked using the .blur() function. While I have a :focus style for accessibility purposes ...

Display successive slidedown notifications consecutively

I want to implement a feature that shows slide down alerts using angularjs. Here is the code I have written: function LoginController($scope, $timeout) { $scope.alerts = [{ name: "Alert 01 something something" }, { name: &qu ...

Delete an element once the ajax request is complete

After closing the modal, I noticed that a div element was left behind causing the screen to become unresponsive. <div class="modal-backdrop fade show"></div> I found that removing this element using the console command below fixed the issue: ...

AngularJS: enhancing $http with custom functionality

I am facing an issue with my simple controller, which looks like this: function MyController($scope, $http) { ... $http.post(url).success(function(data) { console.log(data) }); } MyController.$inject = ['$scope', &ap ...

Submitting req.body.variable_name using Angular

My goal is to successfully post req.body.variable_name. Below you can find my controller and services in Node.js. However, I am encountering an issue where I am receiving 'undefined' back in responseAddROBO. Can you help me identify the mistake? ...

Is it feasible to impersonate a session in PHP by manipulating cookies on the client-side with JavaScript?

Is it possible for an unauthorized visitor to view, delete, or edit session cookies in a PHP web app if HttpOnly cookies are not being used? What happens when a user on a non-session page of a web app sets a cookie with the same name as a session page coo ...

Modify x and y axes in highcharts for stacked columns

Can anyone assist me in finding charts similar to the one shown below? I am interested in utilizing the stacked column charts provided by the highcharts library. However, I need to modify the presentation of the data values as demonstrated in the image. I ...

Error in HTML code when trying to incorporate a JavaScript file

I'm struggling with something seemingly simple - including a JavaScript file in my flat HTML page. Here is the content of my JavaScript file: <script> $(document).ready(function() { $('div').css('background', 'red& ...

Combining the power of Vuforia with the capabilities of Three

I'm having difficulty with the integration of three.js and Vuforia, as I have limited knowledge about OpenGl which makes it challenging to troubleshoot. Our team is working on a small AR app where we aim to utilize Vuforia for tracking and recognitio ...

Understanding how to utilize and manipulate this JSON data using JavaScript

In my code, there is a variable that contains the following data: { "Rows": [ { "New":1, "CachedNumberType":0, "Date":1327479615921, "Type":2, "Number":"123456", "Duration ...