Refresh a particular element using javascript

I'm new to Javascript and I am trying to refresh a specific element (a div) using only Javascript when that div is clicked.

I came across the location.reload() function, but it reloads the entire page which doesn't fit my requirements. Upon clicking the button, I want to display the time taken to click that div.

I'll refrain from sharing the code as it may complicate the question. Essentially, I'm curious if there exists a function similar to location.reload() that I could utilize to target a particular element (div) for refreshing.

Update: Below is the code snippet:

<h1>Test your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can</p;

<p id="timeNeeded"></p>

<div id="circle"></div>

        <script type="text/javascript">

        // defining variables
var myColors = ["green", "blue", "red", "purple", "orange", "black"];
var myShape = ["50px", "inherit"];

var startTime, endTime, timeDiff;
var randColor = myColors[Math.floor(Math.random() * myColors.length)];
var randShape = myShape[Math.floor(Math.random() * myShape.length)];


// function definition: Setting the color and shape of the box
function setStyle () {

    var circle = document.getElementById("circle");
     circle.style.backgroundColor = randColor;
     circle.style.borderRadius = randShape;
}

// function definition: Set start time
function start() {
  startTime = new Date();
}

// function definition: End time and calculate difference
function end() {
  endTime = new Date();
}

// initiate time measurement
start();

// execute styling
setStyle();

// Clicking the button
document.getElementById("circle").onclick = function () {

// reloads the page
// location.reload();

end();
var timeDiff = endTime - startTime;

}
  document.getElementById("timeNeeded").innerHTML = "Your reaction: " + timeDiff

        </script>
    </body>
</html>

Answer №1

To refresh a portion of the webpage without reloading, AJAX can be utilized.

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>

<script>
function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "xmlhttp_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>

Alternatively, if only the content within a specific div needs to be updated, the following code can be used:

<!DOCTYPE html>
<html>
<body>

<div id="demo">
Text 1
</div>
<button type="button" onclick="loadDiv()">Change Content</button>

<script>
function loadDiv() {
  document.getElementById("demo").innerHTML = "Text 1 "  + Math.random(); ;
}
</script>

</body>
</html>

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

How to execute a java class method within a JSP page

Is there a way to trigger a specific Java method when I click a button on a JSP page? I attempted using a scriptlet in the onclick event of the button to create an instance of the class and call the desired method, but unfortunately, it didn't yield t ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

What is the best way to choose an item from a dropdown menu using JavaScript?

Is there a way to set the dropdown value from the client side? Currently, I am loading countries and states using a countries.js file on grid row selection for updating. However, because it is loaded from the client side, I am unable to load country and st ...

ShadCn UI ResizablePanelGroup effortlessly grows within the available area without the need to set a specific height

I'm facing a CSS challenge with the ResizablePanelGroup component. My layout includes a header and a ResizablePanelGroup with 4 panels. The page should take up 100% of the viewport height, and I want other components to be placed within it. Once the H ...

duplicate styling for individual table cells

I am in need of a span element inside a td tag that I am generating within a table. In order to ensure the span fills the td, I have set it as an inline-block with a width and height of 100%. However, when pressing the delete key in the last cell, it star ...

Achieving nested classes in CSS: a comprehensive guide

I am encountering an issue with my CSS while trying to create a dropdown on hover. The problem seems to be related to nested classes inside a div structure. It appears that the dropdown list is not displaying properly, leading me to believe there might be ...

What is the best way to retrieve both the checked and unchecked values from a collection of checkboxes?

Check Out This live Example: I am in the process of creating a list of checkboxes with various data objects: data = [ { Key: "class_id", displayName: "Section ID", enabled: true }, { Key: "room_l4", displayName: "Location", enabled: false }, { Key: "se ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Rearrange the elements in an array containing objects

I am working with an array of objects: const array = [ { id: "5a2524432b68c725c06ac987", customOrder: 1, name: "One", }, { id: "5a2524432b68sgs25c06ac987", customOrder: 2, name: "Two", }, { id: "5a252wfew32b68c725c06a ...

What are the steps to bring in a module from a URL?

I have integrated a Vue.js npm package into my application. However, due to certain reasons, I now need to directly use the CDN URL. Let's assume that this is the CDN link for the library: https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-prot ...

Is it possible to retrieve a specific property from an object in JSON format using Javascript?

As a beginner in JavaScript, I've been diving into the world of objects and trying to grasp how they function. var data = JSON.stringify({name: "Y", age: 1990}); console.log(data); // → {"name":"Y","age":1990} Out of sheer curiosity, I decided to ...

What do I do when I get a "findByIdAndUpdate is not a function" error from my controller after requiring the model

I am currently developing a web application for my company that allows us to access and manage a database of customers and their information using MongoDB, Mongoose, and Express. Our company specializes in reselling used copiers/printers and offering maint ...

Utilize Bootstrap and Flat UI to enhance the design of a div, or duplicate the styles to apply to the navbar

My navigation bar was created using Bootstrap and Flat UI on top of it. However, when I try to incorporate bootstrap+flat ui into another HTML+CSS file that I have, the hexagons end up looking distorted. It seems like my navigation bar only works with flat ...

Guide to presenting pictures from a database using PHP

Currently, my application is able to successfully upload images by saving the file location in a MySQL database. However, I am now facing an issue when trying to display these uploaded images. Below is the code snippet causing problems: include ('co ...

Dynamic data retrieval with the power of JavaScript and AJAX

When attempting to send data using AJAX in PHP, I encountered an issue with my jQuery click function on a button that sends data only when the quantity is greater than 1. The error arises because PHP does not recognize the variables 'name' and &a ...

An innovative way to display or hide a div depending on the multiple selections made in a select2 jQuery field

A select2 jQuery dropdown menu is set up with two options: *For Rent *For Sales If the user selects 'For Rent', specific fields will be displayed below it, as well as for 'For Sales'. The challenge arises when both options are ...

Issue with background/hero video not adjusting its size

I've been experimenting with creating a page that features a video as the background, but no matter what I try, the video never seems to resize properly. The image below shows how it looks: image in question body { margin: 0; } .hero-se ...

Managing the vertical space within a nested accordion section

I've built a custom accordion component, but I'm encountering scrolling issues when trying to use nested levels within the accordion. I'd like to prevent scrolling inside the accordion section and instead have the page scroll below it. Any ...

Sending data using jQuery when a button is clicked

Is there a way to display the text from a text box when a button is clicked? Here's what I have been attempting: <script type="text/javascript> $(function() { $('#button').click(function(){ $.ajax({ type: "PO ...

What is the most efficient way to define the font properties for all H1-H6 headings in a single declaration

Is there a way to set all font properties for H1-H6 headings in one CSS declaration? CSSLint.net is flagging multiple definitions of heading styles as an issue. I currently have specific styles for each heading level: h1 { font-size: 1.8em; margin-top: ...