Using several JavaScript counters concurrently on a single webpage

I am currently organizing tournaments all year round, with prices increasing daily. While the code is functional, I'm struggling to figure out which elements need adjusting to display multiple prices that adjust simultaneously. I attempted changing "rate" to "rate1", but that didn't solve the issue... so it seems variables within should also be modified. Any assistance on this matter would be greatly appreciated. The specific page I'm working on can be found here: -- The snippet below represents what I am currently focusing my efforts on. Thank you in advance for your help.

<div class="eventbox mlk activebox"><img src="https://fiftyallstars.com/Images/jammlk.gif" class="holidayback">
    <span class="eventlabel tourney">MLK DAY SHOWCASE</span><br><div class="numberfont eventdetails">
    January 17-18, 2022<br>
    Grades: 1st-8th<br>
    Current Price: <div class="rate" style="display: inline; font-weight:bold;"></div>
    <script type="text/javascript">
        const days = (date) => Math.ceil(date.getTime() / (24 * 60 * 60 * 1000));
const DEADLINE = days(new Date("2022-01-10"));
const START = days(new Date("2021-10-01"));
const TODAY = days(new Date());
const res = Math.round(400 - 300 * ((DEADLINE - TODAY) / (DEADLINE - START)));
console.log(res);
document.querySelector('.rate').append(`$${res}`)
</script>
<br>
</div>
<table class="buttontable"><tr><td><a href="javascript:void(0);" class="eventlink"><div class="eventbutton">Brackets</div></a></td><td><a href="javascript:void(0);" class="eventlink"><div class="eventbutton">Register</div></a></td></tr></table> 
</div>



<div class="eventbox "><img src="https://fiftyallstars.com/Images/jamabe.png" class="holidayback">
    <span class="eventlabel">PREZ DAY CHALLENGE</span><br><div class="numberfont eventdetails">
    February 17-18, 2022<br>
    Grades: 1st-8th<br>
    Current Price: <div class="rate" style="display: inline; font-weight:bold;"></div>
    <script type="text/javascript">
        const days = (date) => Math.ceil(date.getTime() / (24 * 60 * 60 * 1000));
const DEADLINE = days(new Date("2022-02-10"));
const START = days(new Date("2021-10-01"));
const TODAY = days(new Date());
const res = Math.round(400 - 300 * ((DEADLINE - TODAY) / (DEADLINE - START)));
console.log(res);
document.querySelector('.rate').append(`$${res}`)
</script>
<br>
</div>
<table class="buttontable"><tr><td><a href="javascript:void(0);" class="eventlink"><div class="eventbutton">Brackets</div></a></td><td><a href="javascript:void(0);" class="eventlink"><div class="eventbutton">Register</div></a></td></tr></table> 
</div>

Answer №1

Instead of manually creating each HTML element, it's better to use a loop for generating them, keeping the structure consistent and reducing code duplication.

Check out my approach below:

<div id="eventboxcontainer"></div>
<script type="text/javascript">
    var data = [
    {
        "title" : "MLK DAY SHOWCASE",
        "img" : "https://fiftyallstars.com/Images/jammlk.gif",
        "dateRange" : "January 17-18, 2022",
        "grades" : "1st-8th",
        "deadline" : "2022-01-10",
        "start" : "2021-10-01"
    },
    {
        "title" : "PREZ DAY CHALLENGE",
        "img" : "https://fiftyallstars.com/Images/jamabe.png",
        "dateRange" : "February 17-18, 2022",
        "grades" : "1st-8th",
        "deadline" : "2022-02-10",
        "start" : "2021-10-01"
    }
    ];

    

    var days = (date) => Math.ceil(date.getTime() / (24 * 60 * 60 * 1000));
    var TODAY = days(new Date());

    for (var i = 0; i < data.length; i++) {

        var html = "";

        var DEADLINE = days(new Date(data[i].deadline));
        var START = days(new Date(data[i].start));

        var rate = Math.round(400 - 300 * ((DEADLINE - TODAY) / (DEADLINE - START)));

        html = '<div class="eventbox mlk activebox"><img src="' + data[i].img + '" class="holidayback">'+
               '<span class="eventlabel tourney">' + data[i].title + '</span><br><div class="numberfont eventdetails">'+
               data[i].dateRange + '<br>'+
               data[i].grades + '<br>'+
               'Current Price: <div class="rate" style="display: inline; font-weight:bold;">' + rate + '</div>'+
               '<br>'+
               '</div>'+
               '<table class="buttontable"><tr><td><a href="javascript:void(0);" class="eventlink">'+
               '<div class="eventbutton">Brackets</div></a></td><td><a href="javascript:void(0);" class="eventlink">'+
               '<div class="eventbutton">Register</div></a></td></tr></table> </div>';

        // jQuery can be used for appending
        //$("#eventboxcontainer").append(html);

        // Adding elements in Pure JavaScript way
        var element = document.querySelector("#eventboxcontainer");
        element.insertAdjacentHTML('beforeend', html);


    }

</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

Can directives be inserted within the v-html directive?

I am currently working on some web features, but I have encountered a problem. I was trying to create multiple HTML structures that include Vue directives with v-html, but I couldn't figure it out. So, does anyone know how to render Vue directives wit ...

Inject additional information following user authentication

Hello there! I have successfully developed a REST API using Node.js and StrongLoop, along with an Angular.js based app. After a user logs in, the server sends an accessToken which is stored in cookies. For every request, the accessToken is sent and verif ...

Trouble with Ruby on Rails jQuery interactions when using the tokenInput gem

Currently, I am developing a rails app and attempting to incorporate this gem for a text field https://github.com/exAspArk/rails-jquery-tokeninput Despite having the gem correctly installed and included in my _form.html.erb file, I keep encountering the ...

Looking to silence the audio completely or just mute it for mobile Android Chrome and Safari on iOS?

I am struggling to set the audio tag volume to zero or mute it using jQuery. The muted property works on desktop Chrome but not on Android Chrome. Here's a snippet of my code: song = document.getElementById('audio'); song.volume = 0.0; I h ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

Incorporate a lightbox within a repeater field in advanced custom fields

I have developed a gallery with dynamic pills using advanced custom fields and I need to add a lightbox to it. I've tried several times to add the code for the lightbox but all my attempts have been unsuccessful. I have already added all the necessar ...

The output of element.css('left') is 'auto' despite not being specific to iPhone Safari

I am facing an issue with extracting and setting the left CSS property of an element using Javascript. The element has the left property defined inline, which I can see in Safari's inspect tool on my Mac while debugging for Safari on my phone. Howeve ...

Explain and suggest the necessary parameters for a function

Is there a way to clearly describe the parameters required by my function and make them visible when I am typing my code? For instance, if we consider the ExpressJS render function below, it effectively shows what the callback expects and will return. In ...

Using Bloom Post-Processing in ThreeJS without NPM in Pure JavaScript

I'm in search of a bloom effect for my scene while using an emissive map, similar to what's showcased in this ThreeJS Example. Attempting to decipher the code has left me feeling stuck. The examples rely on NPM, which isn't part of my proje ...

The issue of "Callback is not a function" arises within the selectize framework

Currently, I am working on a yii2-basic project and have implemented the selectize extension for my forms. However, when running this section of the code, an error is returned stating 'callback is not a function'. The field report_cp is a dropdo ...

Tips on transforming JSON data into a hierarchical/tree structure with javascript/angularJS

[ {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"1","zid":"1","statename":"Karnataka"}, {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"2","zid":"1","s ...

Find all LI elements within UL containers that are not contained in a UL element with a specific class using jQuery

How can I select all elements from ul, excluding those with the class not-need? <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <ul class='not ...

Replicate and refresh characteristics

As a newcomer to this platform, I have found stackoverflow to be an invaluable resource over the past year. Currently, I am working on creating a complex form that requires the user to add subgroups. Using jquery (1.5.1 - perhaps it's time for an upd ...

Trouble transferring data between sibling components in Vue.js

In my setup, there are three components where one acts as the parent to the others. I am attempting to pass an object named talk between sibling components by emitting it through an event from FollowedBrowser to LeftBar, and then passing it via props from ...

Node.js routing issues leading to rendering failures

I have been working on a website that involves carpooling with drivers and passengers. When a driver submits their details, they are directed to a URL where they can select the passenger they want to ride with. Here is the code snippet I have written: ap ...

Stop users from skipping ahead in an HTML5 video

Struggling to stop a user from seeking on the video player. I've attempted to bind to the event, but it's not working as expected. Any suggestions on how to successfully prevent this action? @$('#video').bind("seeking", (e) =& ...

Transform JSON data into an HTML table display using JavaScript/JQuery

To retrieve the JSON output on the user interface, I use the following function: $("#idvar").click(function(){ var d1 = document.getElementById("dText"); var d2 = document.getElementById("dJson"); var mytext = d1.textContent; alert(mytext); $.po ...

Using innerHTML to replaceAll also modifies characters within the tags

I created a custom function to emphasize specific strings within a text by surrounding them with span tags and updating the content using the innerHTML property of the targeted element. However, I encountered an issue while working with innerHTML instead ...

Steps for displaying an image from a static file using JavaScript in a Django project

Having an issue retrieving a picture from my static files using a JavaScript function. Here is the JavaScript code in question: <script type="text/javascript"> var url_1 = '{% static "assets/img/stolovi/2.jpg" %}'; function addim ...