Home > Blockchain >  How to do onclick in pure js and HTML
How to do onclick in pure js and HTML

Time:10-26

I'm working on a small project - building digital clocks for multiple time zones - the idea is a have several different time zone clocks and a drop down with more countries to choose from, and the clock should update from the selection. I have a button, in the button I have an id, an "onclick", and a class.

currently I have this in js for all the static clocks:

function getTime(countryTimezone, elementName) {
    let chosenTime = new Date().toLocaleString("en-US", {timeZone: countryTimezone});
    let selectedTime = new Date (chosenTime);

    let hour = selectedTime.getHours();
    let min = selectedTime.getMinutes();
    let sec = selectedTime.getSeconds();

    let timezone = hour   ":"
      min   ":"   sec 

    document.getElementById(elementName)
    .innerHTML = chosenTime;
}

and tried to add this below so that when a country is selected, the clock is updated:

 document.getElementById("countriesDropdown");
//     button.addEventListener("click",function(countryTimezone, elementName){
//         let chosenTime = new Date().toLocaleString("en-US", {timeZone: countryTimezone});
//         let selectedTime = new Date (chosenTime);
    
//         let hour = selectedTime.getHours();
//         let min = selectedTime.getMinutes();
//         let sec = selectedTime.getSeconds();
    
//         let timezone = hour   ":"
//           min   ":"   sec; 
//     })

My HTML button:

<div >
  <div >
    <button id="countriesDropdown" onclick="getTime" >Select a Country</button>
    <ul>
      <li><a href="#">Andorra</a></li>
      <li><a href="#">Dubai</a></li>
      <li><a href="#">Kabul</a></li>
      <li><a href="#">Tirane</a></li>
      <li><a href="#">Yerevan</a></li>
      <li><a href="#">Casey</a></li>
      <li><a href="#">Davis</a></li>
      <li><a href="#">Dumont Durville</a></li>
      <li><a href="#">Mawson</a></li>
      <li><a href="#">Palmer</a></li>
      <li><a href="#">Rothera</a></li>
      <li><a href="#">Syowa</a></li>
      <li><a href="#">Troll</a></li>
      <li><a href="#">Vostok</a></li>
      <li><a href="#">Buenos_Aires</a></li>
      <li><a href="#">Cordoba</a></li>
      <li><a href="#">Salta</a></li>
      <li><a href="#">Jujuy</a></li>
    </ul>
  </div>
</div>

<div id="selectedClock"> 00:00:00</div>

CodePudding user response:

  1. You want a drop down of countries so you should do it with select tag.
  2. Adding onclick attribute in tag is not the best practice so do it with javascript instead.

function getTime(countryTimezone) {
    const chosenTime = new Date().toLocaleTimeString("en-US", {timeZone: countryTimezone});
    document.getElementById('selectedClock').innerHTML = chosenTime;
}

document.querySelector('div.countriesList > select').addEventListener('change', function(){
  getTime(this.value);
});
<div >
  <select>
    <option value="Europe/Andorra">Andorra</option>
    <option value="Asia/Dubai">Dubai</option>
    <option value="Asia/Kabul">Kabul</option>
    <option value="Europe/Tirane">Tirane</option>
  </select>
</div>
<div id="selectedClock"> 00:00:00</div>
Time zones reference: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Hope it helps.

CodePudding user response:

When you define onclick functions, you need to put parentheses. In your getTime function, you want to pass in parameters, but you're passing nothing.

<button id="countriesDropdown" onclick="getTime('time zone here', 'element name here');"  >Select a Country</button>

This code you provided, has a syntax error:

document.getElementById("countriesDropdown");
 button.addEventListener("click",function(countryTimezone, elementName) {
                                                                      ^
// Expected ')' but instead got '{'

You used addEventListener but never closed it, instead, you ended it with the function's parentheses. Additionally, you call getElementById on "countriesDropdown" but you didn't define it in a variable, meaning it's unusable

CodePudding user response:

I think you can use select tag and when select is changing works your function

CodePudding user response:

You should be using select instead

change this

<ul>
    <li><a href="#">Andorra</a></li>
    <li><a href="#">Dubai</a></li>
    <li><a href="#">Kabul</a></li>
    ...

to

<select id="countriesDropdown" >
    <option value="Andorra"></option>
    <option value="Dubai"></option>
    ...   
</select>

In javascipt

 button = document.getElementById("countriesDropdown");
 button.addEventListener("change",getTime);

Do not add the remainder of the function as you did previously. Just the function name is okay.

And in getTime

function getTime() {
    selection = document.getElementById("countriesDropdown");
    let countryTimezone = selection.value;
    let chosenTime = new Date().toLocaleString("en-US", {timeZone: countryTimezone});
    let selectedTime = new Date (chosenTime);
    elementName = "selectedClock";
...

CodePudding user response:

Get the element you're interested in element then add the event listener to that element:
element.addEventListener('click', func);
The function takes a parameter for the event and is often inlined:
element.addEventListener('click', function(e) { ... });

This sample adds the click listener to the button, which just toggles the class "open" so click adds open, click again removes open, to open and close the list (show and hide), and again hides the list when something is chosen.

Each list-item naming a country also gets an event listener to get the country chosen. I'm just writing it to the console; you would update your clock.

const btn = document.getElementById('countriesDropdown');
const list = btn.querySelector('#countriesDropdown   ul');

btn?.addEventListener('click', function(event) {
    list.classList.toggle('open');
});

list.querySelectorAll('li > a')
    ?.forEach(li => {
        li.addEventListener('click', function(e) {
            e.preventDefault();
            const country = e.target.innerText;
            list.classList.toggle('open'); // close the list again when something is chosen
            console.log(`country chosen: ${country}`);
        })
    });
.countriesList ul {
    display: none;
}
.countriesList ul.open {
    display: block;
}
<div >
  <div >
    <button id="countriesDropdown" >Select a Country</button>
    <ul>
      <li><a href="#">Andorra</a></li>
      <li><a href="#">Dubai</a></li>
      <li><a href="#">Kabul</a></li>
      <li><a href="#">Tirane</a></li>
      <li><a href="#">Yerevan</a></li>
      <li><a href="#">Casey</a></li>
      <li><a href="#">Davis</a></li>
      <li><a href="#">Dumont Durville</a></li>
      <li><a href="#">Mawson</a></li>
      <li><a href="#">Palmer</a></li>
      <li><a href="#">Rothera</a></li>
      <li><a href="#">Syowa</a></li>
      <li><a href="#">Troll</a></li>
      <li><a href="#">Vostok</a></li>
      <li><a href="#">Buenos_Aires</a></li>
      <li><a href="#">Cordoba</a></li>
      <li><a href="#">Salta</a></li>
      <li><a href="#">Jujuy</a></li>
    </ul>
  </div>
</div>

<div id="selectedClock">00:00:00</div>

As others mention, I would have used a select with options:

<select id="countriesDropdown">
    <option value="andorra">Andorra</option>
     etc.
</select>

CodePudding user response:

You can use the document.querySelectorAll to capture all the hrefs and attach an event listener to each href like given down below.

countries = document.querySelectorAll('li > a')
for (country of countries) {
  country.addEventListener("click", getTime(country.innerText));
};

function getTime(countryTimezone) {
  let chosenTime = new Date().toLocaleString("en-US", {
    timeZone: countryTimezone
  });
  let selectedTime = new Date(chosenTime);

  let hour = selectedTime.getHours();
  let min = selectedTime.getMinutes();
  let sec = selectedTime.getSeconds();

  let timezone = hour   ":"   min   ":"   sec

  document.getElementById("selectedClock").innerHTML = chosenTime;
}
<div >
  <div >
    <button id="countriesDropdown" >Select a Country</button>
    <ul>
      <li><a href="#">Andorra</a></li>
      <li><a href="#">Dubai</a></li>
      <li><a href="#">Kabul</a></li>
    </ul>
  </div>
</div>

<div id="selectedClock"> 00:00:00</div>

The above code will attach a listener to each of those links and when a country name is clicked it should change the time in your div tag with id - selectedClock.

But this will throw an error because toLocaleDateString method takes one of the options as TimeZone but you are providing an invalid one (Country Name). So you should provide a valid timezone for it. Time zones reference: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Like suggested by others you should use select so that you can specify the country's timezone as its value.

function getTime() {
  countryTimezone = document.getElementById("countriesDropdown").value;
  let chosenTime = new Date().toLocaleString("en-US", {
    timeZone: countryTimezone
  });
  let selectedTime = new Date(chosenTime);

  let hour = selectedTime.getHours();
  let min = selectedTime.getMinutes();
  let sec = selectedTime.getSeconds();

  let timezone = hour   ":"   min   ":"   sec

  document.getElementById("selectedClock").innerHTML = chosenTime;
}

document.getElementById("countriesDropdown").addEventListener("change", getTime);
<div >
  <div >
    <select id="countriesDropdown">
      <option value="IST">India</option>
      <option value="JST">Japan</option>
    </select>
  </div>
</div>

<div id="selectedClock"> 00:00:00</div>

The above code should work for you. When you select a country from the dropdown it will trigger the change event listener attached to the dropdown and will change the time the time in your div tag with id - selectedClock.

Hope this helps.

  • Related