简体   繁体   中英

Change click event for mobile browsers

I want to remove the button (temperature toggling) for browsers which width is less than 400px. Instead i want to touch a div to toggle temperature. I wrote this code but it does not work. "touchTemp" is id of the containing div.

if (window.innerWidth < 400) {
  document.getElementById("touchTemp").addEventListener("click",
    function(e) {
      console.log("Screen width is less than 400px");
      var text = $('#temperature').text();
      if (text.slice(-1) === "F") {
        $("#temperature").html(tempCelsius + " C" + "°");
      } else {
        $("#temperature").html(tempFahrenheit + " F");
      }

      e.preventDefault();
    });
} // end of "if statement"

在此处输入图片说明

Outlined blue div is the area to be touched to toggle temperature.

CodePen Project Link

I would suggest you just add the touch handler along with the click for completeness and ease of testing.

var theElement = document.getElementById("touchTemp");

theElement.addEventListener("click", myFunction, false);
theElement.addEventListener("touchend", myFunction, false);

function myFunction(e) {
  console.log("Screen width is less than 400px");
  var text = $('#temperature').text();
  if (text.slice(-1) === "F") {
    $("#temperature").html(tempCelsius + " C" + "°");
  } else {
    $("#temperature").html(tempFahrenheit + " F");
  }

  e.preventDefault();
  return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM