Home > Mobile >  click event listener method is not working on a specific div
click event listener method is not working on a specific div

Time:12-07

I am trying to add an event listener to my "degree section div" but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the "degree-section" div but to no avail.

Any kind of help is welcome and appreciated

Code:

let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];


//let wind = document.querySelector('.wind');



async function getUrl(city) {

  try {
    let theUrl = url   city   '&appid='   apiKey;
    let response = await fetch(theUrl, {
      mode: 'cors'
    })
    let data = await response.json();
    //Get data from api and change html content based on the recieved data
    let temp_data = data.main.temp
    temp.textContent = temp_data;
    let feels_like_data = data.main.feels_like;
    feels_like.textContent = feels_like_data   "K";
    let humidity_data = data.main.humidity;
    humidity.textContent = humidity_data;
    let {
      icon
    } = data.weather[0];
    locationIcon.innerHTML = `<img src="icons/${icon}.png">`;

    //change K to C
    degree_section.addEventListener('click', () => {
      //logging a message just to check if it is working
      console.log("c")
    })



  } catch (err) {
    let error = document.createElement('span')
    error.className = "error";
    error.textContent = "Location does not exist"
    let top_center_div = document.querySelector('.top-center')
    top_center_div.appendChild(error)
    city_name.textContent = "No city found"
  }
}






searchbtn.addEventListener('click', (e) => {
  let cityName = city.value;
  city_name.textContent = cityName
  console.log(cityName)
  getUrl(cityName)
})
<body>


<div class="loc-container">
    <div class="location">
        <h1 class="city-name">City</h1>
        <div class="weather-icon"><img src="icons/unknown.png" /></div>
   </div>
</div>

<div class="weather-info">

    <div class="degree-section">
        <h2 class="temp">0.0</h2>
        <span>K</span>
    </div>

    <div class="info-section">
        <div class="info-flex">
            <h3 class="feels-like">0K</h3>
            <h4>Feels Like</h4>
        </div>

        <div class="info-flex">
            <h3 class="humidity">0</h3>
            <h4>Humidity</h4>
        </div>

        <div class="info-flex">
            <h3 class="wind">0</h3>
            <h4>Wind</h4>
        </div>
    </div>  
</div>




<div class="top-center">
    <div class="form">
        <input type="text" name="city" id="city" required>
        <label for="city" class="label-name"><span class="search-name">Search City...</span></label>
        
    </div>
    <!-- <i ></i> -->
    <i class="material-icons search-btn" style="font-size: 35px;">search</i>
</div>



<script src="weather.js"></script>

</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This is what "data" looks like

{"coord":{"lon":72.8479,"lat":19.0144},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],"base":"stations","main":{"temp":303.14,"feels_like":303.45,"temp_min":301.09,"temp_max":303.14,"pressure":1014,"humidity":45},"visibility":2500,"wind":{"speed":3.09,"deg":120},"clouds":{"all":20},"dt":1638773692,"sys":{"type":1,"id":9052,"country":"IN","sunrise":1638754125,"sunset":1638793848},"timezone":19800,"id":1275339,"name":"Mumbai","cod":200}

Thank you in advance!

CodePudding user response:

I believe the problem is with

let degree_section_span = degree_section.getElementsByTagName('span')[0];

since it selects the wrong element. Try changing it to

let degree_section_span = weather_sec.querySelector('.check');

and see if it works. You can also change the variable name to something more appropriate, while you're at it.

EDIT:

I think this is what you're trying to do. For the sake of siplicity , I removed everything not related to temp:

let target = weather_sec.querySelector("div.check"),
  temp_data = data.main.temp;
temp.textContent = temp_data;

target.addEventListener('click', () => {
  cel = parseInt(temp_data) - 273.15;
  temp.textContent = cel.toFixed(2);
  temp.nextElementSibling.textContent = "C";
});

CodePudding user response:

So after 48hrs of debugging I finally figured out what is wrong. If you see in my HTML I have a div.top-center at the bottom. And due to some dimension issues in my css file the height of div.top-center spanned the entire page so essentially all of my divs were being wrapped inside div.top-center so even if I assigned a click event to my div.degree-section the target was always div.top-center and that is why the click event was not showing the proper output.

  • Related