I am creating an app that allows the user to check the local weather and temperature in celsius or fahrenheit. However, I am having a problem when toggling between the two unit types when the temperature is clicked on. This is the link to my demo.
And here is my Javascript code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON("https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&units=imperial&appid=a62849f462c6573114f32a691f5d3c3f", function(json) {
var all = JSON.stringify(json);
var weather = JSON.stringify(json.weather[0]["description"]);
weather = weather.slice(1, -1);
var tempFahrenheit = JSON.stringify(json.main.temp);
var tempCelsius = JSON.stringify(json.main.temp * 2);
$("#weather").html(weather);
$("#temp").html(Math.floor(tempFahrenheit) + " °<span id='units'>F</span>");
$("#units").on('click', function() {
if ($(this).text() == "F") {
$("#temp").html(Math.floor(tempCelsius) + " °<span id='units'>C</span>");
} else {
$("#temp").html(Math.floor(tempFahrenheit) + " °<span id='units'>F</span>");
}
});
});
});
}
When you replace the html contents of the #temp div, you lose your event handler on the units div as well. Use event delegation instead. Assign the event on the body tag, but listen for events on the #units div.
Updated code:
$("body").on('click', '#units', function() {
if ($(this).text() == "F") {
$("#temp").html(Math.floor(tempCelsius) + " °<span id='units'>C</span>");
} else {
$("#temp").html(Math.floor(tempFahrenheit) + " °<span id='units'>F</span>");
}
});
Working fork of your Codepen: https://codepen.io/anon/pen/AXzYzR?editors=0010
Related
I am using an ecommerce system where I dont have access to HTML code or anything but I can add custom JS code to alter some things and CSS.
I need to edit the shipping info text which is right to Doba dodania text.
My issue is that the event fires only once and not on every select change event.
Can someone help me why it is firing only once? It was needed to add SetTimeOut too.
Please check the page and console logs here:
https://www.privlacuj.sk/Hacik-Offset-Light-Class-AT-21-cena-za-1ks-d2336_1013278452.htm
My code is:
<script type="text/javascript">
function change_doba_dodania() {
var c757_counter = document.querySelectorAll(".c757").length;
var variant = document.querySelectorAll(".c755.variant").length;
var out_of_stock = document.querySelectorAll(".c757.out-of-stock").length;
console.log(c757_counter);
console.log(variant);
console.log(out_of_stock);
if (out_of_stock > 0) {
console.log("Nincs raktaron");
}
if ( ( c757_counter >= 2 ) && ( out_of_stock == 0 ) ){
var dd_text = document.getElementsByClassName("c757")[1].innerHTML;
console.log(dd_text);
var dd_text_array = dd_text.split(" ");
var dd_final = dd_text_array.filter(String);
console.log(dd_final);
if (dd_final[2] == "zajtra") {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " " + dd_final[9] + " " + dd_final[10] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
} else {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " - " + dd_final[9] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
}
}
}
window.addEventListener('DOMContentLoaded', (event) => {
change_doba_dodania();
});
var variant = document.querySelectorAll(".c755.variant").length;
if (variant > 0){
document.querySelector('.c757 select').addEventListener('change', function()
{setTimeout(change_doba_dodania, 1500)});
document.querySelector('.c757 select').addEventListener('change',() =>
setTimeout(console.log, 1000, "Changed")
)
}
If i got your question, your problem is querySelector.
querySelector only selects the first element with the given class name. If you want to select all the elements with the given class name, you should use querySelectorAll.
document.querySelectorAll(".c757 select").forEach(select => {
select.addEventListener(...)
})
I am trying to make an weather auto refresh which is reloading for changes every 5 seconds. It loads perfectly first time on load but my setinterval is not working correctly. It goes of every 5 seconds but it doesnt update my menu even though changes has been made?
Here is what i got so far:
var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude + "," + position.coords.longitude;
jQuery(document).ready(function(weather) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/lang:AR/forecast/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather_html = ("<h3>Results of " + parsed_json.current_observation.display_location.city +
"</h3>" + "<p>Temperature: " + parsed_json.current_observation.temp_f + "</p>" +
"<p>Current Weather: " + parsed_json.current_observation.weather + "</p>" + "<p>Wind Gusts: " +
parsed_json.current_observation.wind_mph + "mph</p>" + '<img src="http://icons.wxug.com/logos/PNG/wundergroundLogo_black_horz.png" width="200"</img>');
$('#returned_data').html(weather_html).hide().fadeIn("slow");
$(document).ready(function() {
weather(); //Get the initial weather.
setInterval(weather, 600000); //Update the weather every 10 minutes.
});
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون الطقس ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
});
});
}
It doesn't seem to be working.
$(document).ready(function() {
var weather = function() {
... your ajax function here ....
};
weather();
-- add your timer functionality here and wire it to call weather --
});
You have to declare weather as a function and then call the function. Then create your timer to repeatedly call the weather function in order to fulfill your update call.
While I'm writing a detect() function for objects, which the user would get a console.log message when they either mouseover or click an element. I got stuck at adding onclick and onmouseover for two elements (or more, but I can't see) : textarea, and body.
The element that works well is label. When I click it or mouseover it, I get a console.log message.
Here is my Code :
function $count(string){
count = count + 1;
if(count <= 9999){
if(count <= 999){
if(count <= 99){
if(count <= 9){
$log("0000" + String(count) + " : " + string);
}else{
$log("000" + String(count) + " : " + string);
}
}else{
$log("00" + String(count) + " : " + string);
}
}else{
$log("0" + String(count) + " : " + string);
}
}else{
$log(String(count) + " : " + string);
}
}
function $detect(obj, type, script){
if(obj.addEventListener){
obj.addEventListener(type, script, false);
}else{
if(window.attachEvent){
window.attachEvent('on' + type, script);
}else{
console.log("Neither window.addEventListener nor window.attachEvent is working.");
}
}
}
Object.prototype.listen = function(){
if(typeof(this) == "object"){
if(this.constructor == Array){
for(var i = 0; i < this.length; i++){
$detect(this[i], 'click', $count(this[i] + " EVENT : onclick"));
$detect(this[i], 'mouseover', $count(this[i] + " EVENT : onmouseover"));
}
}else{
if(isElement(this)){
$detect(this, 'click', $count(this + " EVENT : onclick"));
$detect(this, 'mouseover', $count(this + " EVENT : onmouseover"));
}else{
console.log("ERROR : this.constructor is not 'Object' or 'Array'.");
return null;
}
}
}else{
console.log("ERROR : typeof(this) is not 'Object'.");
return null;
}
return this;
};
When I perform this action :
document.getElementsByTagName("textarea")[0].listen();
I was willing to receive a console.log when I click it or move the mouse above it. However, when I click the textarea, it doesn't produce the console.log.
I guess the problem is at the detect() or listen().
However I did not want to use element.onclick = function(){}; because it will cover the original function, and I cannot add another onclick to it, so using addEventListener should be better.
Where, or which part, should I change my code?
The problem is at the listen() part :
//...
$detect(this, "click", $count("blahblahblah");
I need to wrap $count("blahblahblah") in function(){ }.
That's the problem. That's all.
Here's my code:
$.getJSON('https://api.syfaro.net/minecraft/1.2/server/info?ip=76.171.110.176&port=25565', function (data) {
document.getElementById('lastUpdate').textContent = "Last Update: " + data.last_update + "(GMT-6)";
document.getElementById('version').textContent = "Minecraft Version: MC Release V" + data.version;
document.getElementById('serverVersion').textContent = "Server Version: Last Update " + data.motd;
if (data.status == "success") {
document.getElementById('online').textContent = "Server is online!";
if (data.players === 0) {
document.getElementById('playerListHTML').textContent = "No players are currently online.";
} else {
for (var i = 0; i < data.playerList.length; i++) {
printList.push(data.playerList[i] + ".png");
var img = document.createElement("img" + [i]);
img.setAttribute("id", "image" + [i]);
document.getElementById("image" + [i]).src = "http://signaturecraft.us/avatars/5/face/" + data.playerList[i] + ".png";
}
//document.getElementById('playerListHTML').textContent = printList;
}
} else {
document.getElementById('online').textContent = "Server is not online... try again later.";
document.getElementById('playersListHTML').textContent = "Server is not online... try again later.";
}
});
Basically, I want to get a JSON from a website's API that gets the list of players online as an array, create an element for each player online, then set the src (image source) to the player's face.
Here is an example of the src URL that I want when I am online: http://signaturecraft.us/avatars/5/face/BtheDestroyer.png
If anyone could figure out how to get this stupid thing working, I would REALLY appreciate the help!
Since you are using jQuery convert all the constructs to use jQuery syntax.
One problem I could see is the created image elements are not added to the dom structure so try
$.getJSON('https://api.syfaro.net/minecraft/1.2/server/info?ip=76.171.110.176&port=25565', function (data) {
$('#lastUpdate').html("Last Update: " + data.last_update + "(GMT-6)")
$('#version').html("Minecraft Version: MC Release V" + data.version)
$('#serverVersion').html("Server Version: Last Update " + data.motd)
if (data.status == "success") {
$('#lastUpdate').html()
if (data.players === 0) {
$('#playerListHTML').html("No players are currently online.")
} else {
$('#playerListHTML').empty()
$.each(data.playerList, function (idx, player) {
$('<img/>', {
id: 'image[' + idx + ']',
src: "http://signaturecraft.us/avatars/5/face/" + player + ".png"
}).appendTo('#playerListHTML')
})
}
} else {
$('#online').html("Server is not online... try again later.")
$('#playersListHTML').html("Server is not online... try again later.")
}
});
Demo: Fiddle
Anyone have an idea why my jQuery click won't work?
It's attached to a hyperlink.
jQuery(function ($) {
$(".delete").click(function(e) {
alert("Hello");
});
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message',
'<b>' + $messageTitle.val() + '</b>' + ' - '
+ $messageBox.val() + ' ' + '[' +
'<a class="delete" href="#">Delete</a>' + ']');
$messageTitle.val('');
$messageBox.val('');
}
});
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
Since the delete links are dynamically generated, you need to use event delegation:
$('#chat').on('click', '.delete', function(e) {
alert("Hello");
});
Hello try to modify your jquery initialization like this:
(function($){ }(jQuery)
If your script still doesn't fire the click event, check if $messageForm exists, using console.log($messageForm). You can modify var $messageForm in var messageForm from what I seen that variable does not need a scope so wide. I hope this could help you