Erase the contents of a div by clicking a button

I am currently working on a game project that utilizes drag-and-drop functionality, similar to Blockly and Scratch. One of the key features I am trying to implement is the ability to clear the contents of a target container by clicking a Reset button. Despite my efforts to code this feature, I have not been successful so far.

Below are the relevant snippets from my code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Game Project - Drag-and-Drop</title>
    <script src="{{ url_for('static',filename='vendor/jquery/jquery.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/sb-admin-2.min.js') }}"></script>
</head>

<body id="page-top">
    <div id="wrapper">
        <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordion_sidebar">
        <!-- Game Commands -->
            <a class="sidebar-brand d-flex align-items-center justify-content-center">
                <div class="sidebar-brand-icon rotate-n-15"><i class="fas fa-laugh-wink"></i></div>
                <div class="sidebar-brand-text mx-3">Game Commands</div>
            </a>
            <div class="commands">
                <div class="draggable">
                    <input type="button" class="btn-forward" id="forward" value="Forward" draggable="true"></button>
                </div>
                <div class="draggable">
                    <input type="button" class="btn-backward" id="backward" value="Backward" draggable="true"></button>
                </div>
                <div class="draggable">
                    <input type="button" class="btn-right" id="right" value="Right" draggable="true"></button>
                </div>
                <div class="draggable">
                    <input type="button" class="btn-left" id="left" value="Left" draggable="true"></button>
                </div>
                <div class="draggable">
                    <input type="button" class="btn-repeat" id="repeat" value="Repeat" draggable="true"></button>
                </div>
            </div>
        </ul>
        <!-- Content Area -->
        <div class="container-fluid">
            <div class="row">
                <div class="col-xl-12 col-lg-12">
                    <div class="card shadow mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <div class="container" id="commands"></div>
                                    <button id="reset" class="btn btn-lg btn-primary" value="Reset">Reset</button>
                                </div>
                            </div>
                        </div> 
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" \
    integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" \
    crossorigin="anonymous" referrerpolicy="no-referrer">
</script>

<script type="text/javascript">
    $(document).ready(function()
    {
        $("button").click(function()
        {
            $("#commands").empty();
        });
    });
</script>
</html>

Answer №1

Modified Version:

<button id="reset" class="btn btn-lg btn-primary" value="Reset">Reset</button>

<script type="text/javascript">
    $(document).ready(function()
    {
        $("#reset").click(function()
        {
            $("#commands").empty();
        });
    });
</script>

Answer №2

If you want to toggle the visibility of divs using just vanilla JavaScript, you can do so with the following simple example:

<div id="mainContainer">This is the content inside the div</div>
<button id="toggleButton" value="Toggle"&mt;Toggle Div</button>

<script>
    toggleButton.addEventListener('click', () => {
        mainContainer.style.display === 'none' ? mainContainer.style.display = 'block' : mainContainer.style.display = 'none';
        // You can also use mainContainer.style.visibility = 'hidden'; if you want to hide the div but still leave space
    });
</script>

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

Accessing JSON key by value alone

Imagine you have a variable storing the value of a key in a JSON object. Let's see... var stooges = [ {"id" : "a", "name" : "Moe"}, {"id" : "b", "name" : "Larry"}, {"id" : "c", "name" : "Shemp"} ]; var stooge = "Larry"; I am seeking gui ...

Struggling to make image uploading function with Flask and JQuery

Utilize the code snippet below to submit forms and retrieve a modified version of text from Flask using AJAX and JQuery: from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route('/') def index(): return re ...

Sort choices based on the optgroup category label text

I want to create a system where the user can select a game from one dropdown menu and then see only the consoles that game is available on in another dropdown menu. For example, if the user selects a game like Forza Horizon which is available on multiple c ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

Structure of Divs with Bootstrap

Looking to create a layout with two divs side by side like the image below: Example However, when the screen width increases, the layout changes to this: Current Here is the code: Is there anyone skilled in this area who can guide me through it? Your a ...

Updating array properties in a JSON object using a foreach loop will automatically update all corresponding keys

Having a slight headache working on this particular issue. My aim is to construct an array of JSON objects using a foreach loop, and everything is functioning perfectly except for one property. The problematic property is actually an array that gets update ...

Sending user input data from a React text field to a function as arguments

Below are input fields, from which I need to retrieve the entered values and pass them to the onClick event of the button displayed below. <input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/> <input type=" ...

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

When a hard refresh is triggered, Vue's navigation guard takes precedence over localStorage

Currently, I am working on implementing a permission check for users before they can access a specific route. I have experimented with using both route.beforeEach and route.beforeResolve. Everything functions as expected if the localStorage within the tab ...

Converting a Jquery object into a Javascript object

Can someone help me decipher this piece of code? //... obj.dd.on('click', function(event){ $(this).toggleClass('active'); return false; }); //... $(function() { var dd = new DropDown( $('#dd') ); $(doc ...

Using jQuery Modal Dialog with ASP.NET MVC 2

In my ASP.NET Mvc 2 application, I have a grid of user info. When a user is clicked, a jQuery Modal dialog opens allowing me to edit and save the user's information successfully. I am now looking for assistance on implementing validation on this moda ...

What is the best way to measure the timing of consecutive events within a web browser, utilizing JavaScript within an HTML script tag?

Currently delving into the realm of JavaScript, transitioning from a Java/Clojure background, I am attempting to implement a basic thread-sleep feature that will display lines of text on the screen at one second intervals. Initially, I considered using t ...

Only fire the click event of the parent div if none of the child elements are clicked

Here is a fiddle I've prepared for reference: https://jsfiddle.net/9m4bgyq8/16/ The issue I am facing is that I am attempting to wrap a checkbox and label within a div, and apply a click event to the div. The intention is for the click event to only ...

The anchor tag is not being used in the function call in an Angular application

Having trouble with calling the logout function inside the login controller. The setup involves a simple login and logout system using ui-router. After successfully logging in and navigating to another page, I encountered issues with calling the logout fu ...

Excessive ajax requests occurring when the options in the form are altered

My website contains two main sections: (1) search criteria, which include selection boxes in a form used to access database information, and (2) a div where the results are displayed. The initial page load serializes default values from the form and sends ...

Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not bein ...

Using AngularJS $http.jsonp() method to interface with Google Maps Distance Matrix API

I am currently working on integrating the Google Maps Distance Matrix API into my project to calculate distances between two points using specific coordinates. My implementation involves AngularJS and the $http.jsonp() method to make requests to the API: ...

Using jQuery to include the value of an array index in the output

Looking for guidance on jQuery & JavaScript. I have successfully implemented code that adds a new text input field based on the user's selection from a dropdown select field. <script> $(function() { var input = $('<input placeholder= ...

Using ThreeJS to project a mouse click onto the XZ plane

I am currently working on implementing offline routing in a 3D map within a ThreeJS scene. My goal is to allow the user to click on a point and have a cube navigate to that point. While the navigation functionality is working correctly, I am facing an issu ...

What could be causing my carousel slider images to not adapt to different screen sizes?

I recently added a carousel slider to my website, and while it looks great on larger screens like desktops and laptops, I noticed that the images are not scaling properly when viewed on smaller screen widths. This has resulted in non-responsiveness which i ...