I am working on a local weather site through freecodecamp. I was wondering if anyone could help me figure out how to assign jQuery to show parenthesis around negative numbers. i.e. when it is -5 degrees I am trying to get it to say (-5).
Here is the jQuery I am currently working with...
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var long;
var lat;
lat = position.coords.latitude;
long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=79b001616877b59c717616181ee219ec";
$.getJSON(api, function(info) {
var farh;
var cels;
var kelvin;
var tempMin;
var minTemp;
var tempMax;
var maxTemp;
var tempMinC;
var minTempC;
var tempMaxC;
var maxTempC;
var strF = ("\u00B0'F'");
var tempSwitch = false;
kelvin = info.main.temp;
farh = Math.round((kelvin) * (9 / 5) - 459.67);
cels = Math.round(kelvin - 273);
tempMinC = info.main.temp_min;
minTempC = Math.round(tempMinC - 273);
tempMaxC = info.main.temp_max;
maxTempC = Math.round(tempMaxC - 273);
tempMin = info.main.temp_min;
minTemp = Math.round((tempMin) * (9 / 5) - 459.67);
tempMax = info.main.temp_max;
maxTemp = Math.round((tempMax) * (9 / 5) - 459.67);
var city = info.name;
var weatherInfo = info.weather[0].description;
var forecastLow = minTemp;
var forecastHigh = maxTemp;
var forecastLowC = minTempC;
var forecastHighC = maxTempC;
var currCond = info.weather[0].icon;
$('#farh').html(farh);
$('#city').html(city);
$('#weatherInfo').html(weatherInfo);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
$('#currCond').html(currCond);
$('#switch').click(function() {
if (tempSwitch === false) {
$('#farh').html(cels);
$('#forecastLow').html(forecastLowC)
$('#forecastHigh').html(forecastHighC)
tempSwitch = true;
} else {
$('#farh').html(farh);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
tempSwitch = false;
}
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2 class="weather-header" id="city"></h2>
<h1><span class="curr-temp" id="farh"></span><span class="curr-temp">°</span></h1>
<div class="col-md-5"></div>
<div class="col-md-2">
<label class="switched">
<input type="checkbox" id="switch">
<div class="slider"></div>
</label>
</div>
<div class="col-md-5"></div>
<h3><span class="hi-lo" id="forecastLow"></span> Low - <span class="hi-lo" id="forecastHigh"></span> High</h3>
<p class="forecast" id="weatherInfo"></p>
You can create a function like this to format your Output:
function formatTemperature(value){
if(value < 0)
return "(" + value + ")";
else
return value;
};
and wrap your values calling this function, passing the values.
I've updated your snippet example.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var long;
var lat;
lat = position.coords.latitude;
long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=79b001616877b59c717616181ee219ec";
$.getJSON(api, function(info) {
var farh;
var cels;
var kelvin;
var tempMin;
var minTemp;
var tempMax;
var maxTemp;
var tempMinC;
var minTempC;
var tempMaxC;
var maxTempC;
var strF = ("\u00B0'F'");
var tempSwitch = false;
kelvin = info.main.temp;
farh = Math.round((kelvin) * (9 / 5) - 459.67);
cels = Math.round(kelvin - 273);
tempMinC = info.main.temp_min;
minTempC = Math.round(tempMinC - 273);
tempMaxC = info.main.temp_max;
maxTempC = Math.round(tempMaxC - 273);
tempMin = info.main.temp_min;
minTemp = Math.round((tempMin) * (9 / 5) - 459.67);
tempMax = info.main.temp_max;
maxTemp = Math.round((tempMax) * (9 / 5) - 459.67);
var city = info.name;
var weatherInfo = info.weather[0].description;
var forecastLow = minTemp;
var forecastHigh = maxTemp;
var forecastLowC = minTempC;
var forecastHighC = maxTempC;
var currCond = info.weather[0].icon;
function formatTemperature(value){
if(value < 0)
return "(" + value + ")";
else
return value;
}
$('#farh').html(farh);
$('#city').html(city);
$('#weatherInfo').html(weatherInfo);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
$('#currCond').html(currCond);
$('#switch').click(function() {
if (tempSwitch === false) {
$('#farh').html(formatTemperature(cels));
$('#forecastLow').html(formatTemperature(forecastLowC));
$('#forecastHigh').html(formatTemperature(forecastHighC));
tempSwitch = true;
} else {
$('#farh').html(formatTemperature(farh));
$('#forecastLow').html(formatTemperature(forecastLow));
$('#forecastHigh').html(formatTemperature(forecastHigh));
tempSwitch = false;
}
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2 class="weather-header" id="city"></h2>
<h1><span class="curr-temp" id="farh"></span><span class="curr-temp">°</span></h1>
<div class="col-md-5"></div>
<div class="col-md-2">
<label class="switched">
<input type="checkbox" id="switch">
<div class="slider"></div>
</label>
</div>
<div class="col-md-5"></div>
<h3><span class="hi-lo" id="forecastLow"></span> Low - <span class="hi-lo" id="forecastHigh"></span> High</h3>
<p class="forecast" id="weatherInfo"></p>
Related
So I have the following code, As you can see in the HTML I have a div with id=clock and an input element also with id=clock, basically if i remove the div or comment it out, the input element works fine, on the html page the clock in the input element will display the time, I would prefer it to use the div element for styling purposes; however, if i comment out the input element and use the div it does not count up, I think I understand why but I cant seem to fix it. Can someone help explain how I can do this using the following code?
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
// Start-Stop Function
function startstop() {
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if (flagclock == 0) {
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
} else {
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
}
//Increment function
function counter(starttime) {
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if (flagstop == 1) {
timediff = timediff + stoptime
}
if (flagclock == 1) {
clock.value = formattime(timediff, '');
refresh = setTimeout('counter(' + starttime + ');', 10);
} else {
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime, roundtype) {
if (roundtype == 'round') {
var ds = Math.round(rawtime / 100) + '';
} else {
var ds = Math.floor(rawtime / 100) + '';
}
var sec = Math.floor(rawtime / 1000);
var min = Math.floor(rawtime / 60000);
ds = ds.charAt(ds.length - 1);
if (min >= 60) {
startstop();
}
sec = sec - 60 * min + '';
if (sec.charAt(sec.length - 2) != '') {
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
} else {
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if (min.charAt(min.length - 2) != '') {
min = min.charAt(min.length - 2) + min.charAt(min.length - 1);
} else {
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
// reset function
function resetclock() {
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
output.value = '';
splitcounter = 0;
if (flagclock == 1) {
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
} else {
clock.value = "00:00:0";
}
}
//Split function
function splittime() {
if (flagclock == 1) {
if (splitdate != '') {
var splitold = splitdate.split(':');
var splitnow = clock.value.split(':');
var numbers = new Array();
var i = 0
for (i; i < splitold.length; i++) {
numbers[i] = new Array();
numbers[i][0] = splitold[i] * 1;
numbers[i][1] = splitnow[i] * 1;
}
if (numbers[1][1] < numbers[1][0]) {
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if (numbers[2][1] < numbers[2][0]) {
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
var mzeros = (numbers[0][1] - numbers[0][0]) < 10 ? '0' : '';
var szeros = (numbers[1][1] - numbers[1][0]) < 10 ? '0' : '';
output.value += '\t+' + mzeros + (numbers[0][1] - numbers[0][0]) + ':' + szeros + (numbers[1][1] - numbers[1][0]) + ':' + (numbers[2][1] - numbers[2][0]) + '\n';
}
splitdate = clock.value;
output.value += (++splitcounter) + '. ' + clock.value + '\n';
}
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" id='btn' value="Start" onclick="startstop()" ;>
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock()" ;>
<div id="clock" class="timerClock">00:00:00</div><br>
<!-- Clock 2 -->
<input id="clock" class="timerClock" type="text" value="00:00:0" style="text-align: center;" readonly=""><br>
<!-- Split Button -->
<input id="splitbutton" class="buttonZ" style="width: 120px; margin-right: 170px" type="button" value="Split Time" onclick="splittime();">
<!-- output for split times -->
<textarea id="output" spellcheck="false"></textarea>
You are using clock.value to set the contents of the <input> element. This will not work for <div> elements; you will need to use innerHTML instead:
clock = document.getElementById('clock'); //div#clock
// ...
clock.innerHTML = formattime(timediff, '');
have a div with id=clock and an input element also with id=clock,
This is bad. ID have to be UNIQUE. This is why when you have both present ( with same id ) the counter doesn't work. It selects just the first element with id clock which is the div.
It doesn't select the input. As you can see getElementById is singular. If you want to select both of them, add a common class and select that with getElementsByClassName(className) ( notice the plural Elements compared to Element from the ID selector ) or querySelectorAll(className) and loop through them.
I added clock-div as the id on the div
Also. div element does not have a value attribute ( unlike input ). To get or edit/manipulate the text inside a div element you should use div.innerText instead of div.value. As a side note, div can have HTML inside it (input can't) . You can access it with div.innerHTML
So basically you need to change the id of the div ( if you also want to keep the input ) and change clock.value to clock.innerText everywhere.
Another option would be to keep both input and div. And assign the value of the input to the div.innerText.
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
// Start-Stop Function
function startstop() {
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if (flagclock == 0) {
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
} else {
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
}
//Increment function
function counter(starttime) {
output = document.getElementById('output');
// change here id
clock = document.getElementById('clock-div');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if (flagstop == 1) {
timediff = timediff + stoptime
}
if (flagclock == 1) {
clock.innerText = formattime(timediff, '');
refresh = setTimeout('counter(' + starttime + ');', 10);
} else {
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime, roundtype) {
if (roundtype == 'round') {
var ds = Math.round(rawtime / 100) + '';
} else {
var ds = Math.floor(rawtime / 100) + '';
}
var sec = Math.floor(rawtime / 1000);
var min = Math.floor(rawtime / 60000);
ds = ds.charAt(ds.length - 1);
if (min >= 60) {
startstop();
}
sec = sec - 60 * min + '';
if (sec.charAt(sec.length - 2) != '') {
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
} else {
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if (min.charAt(min.length - 2) != '') {
min = min.charAt(min.length - 2) + min.charAt(min.length - 1);
} else {
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
// reset function
function resetclock() {
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
output.value = '';
splitcounter = 0;
if (flagclock == 1) {
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
} else {
clock.innerText = "00:00:0";
}
}
//Split function
function splittime() {
if (flagclock == 1) {
if (splitdate != '') {
var splitold = splitdate.split(':');
var splitnow = clock.value.split(':');
var numbers = new Array();
var i = 0
for (i; i < splitold.length; i++) {
numbers[i] = new Array();
numbers[i][0] = splitold[i] * 1;
numbers[i][1] = splitnow[i] * 1;
}
if (numbers[1][1] < numbers[1][0]) {
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if (numbers[2][1] < numbers[2][0]) {
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
var mzeros = (numbers[0][1] - numbers[0][0]) < 10 ? '0' : '';
var szeros = (numbers[1][1] - numbers[1][0]) < 10 ? '0' : '';
output.value += '\t+' + mzeros + (numbers[0][1] - numbers[0][0]) + ':' + szeros + (numbers[1][1] - numbers[1][0]) + ':' + (numbers[2][1] - numbers[2][0]) + '\n';
}
splitdate = clock.innerText;
output.innerText += (++splitcounter) + '. ' + clock.value + '\n';
}
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" id='btn' value="Start" onclick="startstop()" ;>
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock()" ;>
<div id="clock-div" class="timerClock">00:00:00</div><br>
<!-- Clock 2 -->
<input id="clock" class="timerClock" type="text" value="00:00:0" style="text-align: center;" readonly=""><br>
<!-- Split Button -->
<input id="splitbutton" class="buttonZ" style="width: 120px; margin-right: 170px" type="button" value="Split Time" onclick="splittime();">
<!-- output for split times -->
<textarea id="output" spellcheck="false"></textarea>
I want to make a "drink counter". There are 3 inputs which add another drink onclick. Every drink has a specific value in alcohol (var bier, var wein, var soju).
So on every count up (click), the script is supposed to:
count up the value in the respective input [this works]
add up all the numbers and drinks multiplied by their alcohol value, so added_up = bier_full + soju_full + wein_full;
If you look at the code, you will notice that I'm quite the noob. Help would be much appreciated. I can't think of a way to add all the drinks*alc. values up and display them in the id="status".
HTML:
var full = 100;
var bier = 12.7;
var wein = 10;
var soju = 3.5;
status = document.getElementById("status");
var bier_c = parseInt(document.getElementById("beer").value);
var soju_c = parseInt(document.getElementById("soju").value);
var wein_c = parseInt(document.getElementById("wine").value);
var bier_i = document.getElementById("bier_info");
var soju_i = document.getElementById("soju_info");
var wein_i = document.getElementById("wein_info");
function reset() {
bier_c = 0;
soju_c = 0;
wein_c = 0;
document.getElementById("beer").value = "0";
document.getElementById("soju").value = "0";
document.getElementById("wine").value = "0";
};
function bier_s() {
bier_c++;
document.getElementById("beer").value = bier_c;
bier_full = bier_c * bier;
bier_i.innerHTML = bier_full;
return bier_full;
};
function soju_s() {
soju_c++;
document.getElementById("soju").value = soju_c;
soju_full = soju_c * soju;
soju_i.innerHTML = soju_full;
return soju_full;
};
function wein_s() {
wein_c++;
document.getElementById("wine").value = wein_c;
wein_full = wein_c * wein;
wein_i.innerHTML = wein_full;
return wein_full;
};
added_up = bier_full + soju_full + wein_full;
alert(added_up);
<label>Beer</label><input id="beer" type="button" style="width: 50px;" onclick="bier_s();" value="0">
<label>Soju</label><input id="soju" type="button" style="width: 50px;" onclick="soju_s();" value="0">
<label>Wine</label><input id="wine" type="button" style="width: 50px;" onclick="wein_s();" value="0">
<br/>
<h2 class="c_red" id="status">Let's go!</h2>
<div class="am_info">
<p>Bier: <span id="bier_info"></span></p>
<p>Soju: <span id="soju_info"></span></p>
<p>Wine: <span id="wein_info"></span></p>
</div>
just add a method that runs every time the other methods runs =D
var full = 100;
var bier = 12.7;
var wein = 10;
var soju = 3.5;
var bier_full = 0, soju_full = 0, wein_full = 0;
status = document.getElementById("status");
var bier_c = parseInt(document.getElementById("beer").value);
var soju_c = parseInt(document.getElementById("soju").value);
var wein_c = parseInt(document.getElementById("wine").value);
var bier_i = document.getElementById("bier_info");
var soju_i = document.getElementById("soju_info");
var wein_i = document.getElementById("wein_info");
function reset() {
bier_c = 0;
soju_c = 0;
wein_c = 0;
document.getElementById("beer").value = "0";
document.getElementById("soju").value = "0";
document.getElementById("wine").value = "0";
};
function bier_s() {
bier_c++;
document.getElementById("beer").value = bier_c;
bier_full = bier_c * bier;
bier_i.innerHTML = bier_full;
addUp()
return bier_full;
};
function soju_s() {
soju_c++;
document.getElementById("soju").value = soju_c;
soju_full = soju_c * soju;
soju_i.innerHTML = soju_full;
addUp()
return soju_full;
};
function wein_s() {
wein_c++;
document.getElementById("wine").value = wein_c;
wein_full = wein_c * wein;
wein_i.innerHTML = wein_full;
addUp()
return wein_full;
};
function addUp(){
added_up = bier_full + soju_full + wein_full;
alert(added_up);
}
<label>Beer</label><input id="beer" type="button" style="width: 50px;" onclick="bier_s();" value="0">
<label>Soju</label><input id="soju" type="button" style="width: 50px;" onclick="soju_s();" value="0">
<label>Wine</label><input id="wine" type="button" style="width: 50px;" onclick="wein_s();" value="0">
<br/>
<h2 class="c_red" id="status">Let's go!</h2>
<div class="am_info">
<p>Bier: <span id="bier_info"></span></p>
<p>Soju: <span id="soju_info"></span></p>
<p>Wine: <span id="wein_info"></span></p>
</div>
I am trying to change one image source with id using javascript, also I would like to add/remove width to the picture depending on whether we click on + or - button.
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.src == "images/soleil.jpg") {
sun_to_eclipse.src = "images/eclipse.jpg";
} else {
sun_to_eclipse.src = "images/soleil.jpg";
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.style.width + "20px"
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.style.width - "20px"
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("load", setupListeners);
<div id="doc">
<div id="buttons">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://pbs.twimg.com/profile_images/641353910561566720/VSxsyxs7_400x400.jpg" alt="sunny" />
</div>
Any idea what's wrong?
To Fetch the Width use .clientWidth instead of .style.width
So for addpx use sun_to_eclipse.clientWidth + 20 + "px"; and
for minus use sun_to_eclipse.clientWidth - 20 + "px";
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.src == "https://camo.githubusercontent.com/e9c5fe6cb160f55f564723b8c1679170c74f5e53/687474703a2f2f73392e706f7374696d672e6f72672f7a336e707077797a332f73686565705f333530782e6a7067") {
sun_to_eclipse.src = "http://www.ptahai.com/wp-content/uploads/2016/06/Best-Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg";
} else {
sun_to_eclipse.src = "https://camo.githubusercontent.com/e9c5fe6cb160f55f564723b8c1679170c74f5e53/687474703a2f2f73392e706f7374696d672e6f72672f7a336e707077797a332f73686565705f333530782e6a7067";
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.clientWidth <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.clientWidth + 20 + "px";
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.clientWidth >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.clientWidth - 20 + "px";
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("click", setupListeners);
#sun {
width: 300px;
}
<div id="doc">
<div id="buttons">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_1280.jpg" alt="sunny" />
</div>
the problem is with your setting widths. style.width will return text with some number plus the unit at the end. use offsetWidth property.
var sun = false;
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun == false) {
sun_to_eclipse.src = "images/eclipse.jpg";
sun = true;
} else {
sun_to_eclipse.src = "images/soleil.jpg";
sun = false;
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth + 20 + "px"
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth - 20 + "px"
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("load", setupListeners);
<div id="doc">
<div id="buttons">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://pbs.twimg.com/profile_images/641353910561566720/VSxsyxs7_400x400.jpg" alt="sunny" />
</div>
IMAGE ONCLICK: its not working properly because img.src contains the full address to the image. eg
document.getElementById("sun").src;
"file:///C:/Users/Abhinav/Desktop/images/soleil.jpg"
you can fix that using a variable
var sun = false;
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun == false) {
sun_to_eclipse.src = "images/eclipse.jpg";
sun = true;
} else {
sun_to_eclipse.src = "images/soleil.jpg";
sun = false;
}
}
Making use of offsetWidth to achieve this.
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.src == "images/soleil.jpg") {
sun_to_eclipse.src = "images/eclipse.jpg";
} else {
sun_to_eclipse.src = "images/soleil.jpg";
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth + 20 + "px"
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth - 20 + "px"
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("load", setupListeners);
<div id="doc">
<div id="buttons">
<button id="plus" onClick =>+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://pbs.twimg.com/profile_images/641353910561566720/VSxsyxs7_400x400.jpg" alt="sunny" />
</div>
This is the javascript code:
/**
* Created by Alejandro on 25/02/2016.
*/
var aantalKoppels = 2;
function setup(){
var btnToevoegen = document.getElementById("btnToevoegen");
btnToevoegen.addEventListener("click", koppelToevoegen);
var btnReplace = document.getElementById("btnReplace");
btnReplace.addEventListener("click", update);
}
function koppelToevoegen() {
var parameterDataKoppel = document.createElement("div");
var labelParameter = document.createElement("label");
labelParameter.innerHTML = "Parameter:";
labelParameter.setAttribute("for", "parameter" + aantalKoppels);
var parameter = document.createElement("input");
parameter.id = "parameter" + aantalKoppels;
parameter.setAttribute("type", "text");
var labelData = document.createElement("label");
labelData.innerHTML = "Data:";
labelData.setAttribute("for", "data" + aantalKoppels);
var data = document.createElement("input");
data.id = "data" + aantalKoppels;
data.setAttribute("type", "text");
parameterDataKoppel.appendChild(labelParameter);
parameterDataKoppel.appendChild(parameter);
parameterDataKoppel.appendChild(labelData);
parameterDataKoppel.appendChild(data);
var parameterDataKoppels = document.getElementById("parameterDataKoppels");
parameterDataKoppels.appendChild(parameterDataKoppel);
aantalKoppels++;
}
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
var template = document.getElementById("template");
vervangAlles(template, parameterDataKoppels);
}
function vervangAlles(template, parameterDataKoppels) {
for(var i = 0; i < parameterDataKoppels.length; i++) {
var result = vervang(template, parameterDataKoppels[i][0], parameterDataKoppels[i][1]);
template = result;
}
var output = document.getElementById("txtOutput");
output.innerHTML = template;
return template;
}
function vervang(template, parameter, data) {
var result = template.substring(0, template.indexOf(parameter)) + data;
var i = template.indexOf(parameter) + parameter.length;
while(template.indexOf(parameter, i) !== -1) {
var indexVolgende = template.indexOf(parameter, i);
result += (template.substring(i, indexVolgende)) + data;
i = indexVolgende + parameter.length;
}
result += template.substring(i, template.length);
return result;
}
window.addEventListener("load",setup,false);
This code should take a template (String), parameters (String word out of text) and data (String) as input to then replace al the parameters in the text by the String data. I do get an error which I can't figure out at the first line in the last function:
Uncaught TypeError: template.indexOf is not a functionvervang # ReplaceFunction.js:61vervangAlles # ReplaceFunction.js:52update # ReplaceFunction.js:47
this is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" charset="utf-8" src="../scripts/ReplaceFunction.js"></script>
<title>ReplaceFunction</title>
</head>
<body>
<div>
<label for="template">Template:</label>
<input id="template" type="text" />
</div>
<div id="parameterDataKoppels">
<div>
<label for="parameter1">Parameter:</label>
<input id="parameter1" type="text" />
<label for="data1">Data:</label>
<input id="data1" type="text" />
</div>
</div>
<input id="btnToevoegen" type="button" value="Koppel toevoegen" />
<input id="btnReplace" type="button" value="Replace" />
<p id="txtOutput">geen output</p>
</body>
</html>
I hope somebody knows why I get this error.
It seems like your 'update' should be
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
//var template = document.getElementById("template");
var template = document.getElementById("template").value;
vervangAlles(template, parameterDataKoppels);
}
Hello i have some html like this:
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
And some JS:
jQuery(document).ready(function($) {
var col = $('.preview').find('.col-md-4 .sceneName');
var urls = [];
var ids = [];
col.each(function(i) {
var yy = $(this).closest('.col-md-4').find('a').attr('href');
var xx = $(this).closest('.col-md-4').attr('id');
urls.push(yy);
ids.push(xx);
});
var dataUrls = function() {
$.each(urls, function (i, url) {
$.ajax({
url: url,
type: 'POST',
success: function (data) {
var apronFactor = (($(data).find('.table.table-bordered tr:eq(6) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var apronPrice = ($(data).find('.table.table-bordered tr:eq(6) td:eq(3)').text()).replace(/\s+/g, '');
var apronPriceMR = apronPrice.substring(0, apronPrice.length - 2);
var apronPriceToNum = apronPriceMR*1;
var apronTotalPrice = apronFactor * apronPriceToNum;
/**/
var plankFactor = (($(data).find('.table.table-bordered tr:eq(7) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var plankPrice = ($(data).find('.table.table-bordered tr:eq(7) td:eq(3)').text()).replace(/\s+/g, '');
var plankPriceMR = plankPrice.substring(0, plankPrice.length - 2);
var plankPriceToNum = plankPriceMR*1;
var plankTotalPrice = plankFactor * plankPriceToNum;
/**/
var tentFactor = (($(data).find('.table.table-bordered tr:eq(8) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var tentPrice = ($(data).find('.table.table-bordered tr:eq(8) td:eq(3)').text()).replace(/\s+/g, '');
var tentPriceMR = tentPrice.substring(0, tentPrice.length - 2);
var tentPriceToNum = tentPriceMR*1;
var tentTotalPrice = tentFactor * tentPriceToNum;
/**/
var totalOptionsPrice = apronTotalPrice + plankTotalPrice + tentTotalPrice;
/**/
var complexWithoutOptionsPrice = ($(data).find('#cel_1 > .value').text()).replace(/\s+/g, ''); //cWOP
var cWOPMR = complexWithoutOptionsPrice.substring(0, complexWithoutOptionsPrice.length - 2);
var cWOPToNum = cWOPMR * 1;
/**/
var newTotalPrice = cWOPToNum + totalOptionsPrice;
var newTotalPriceToString = newTotalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "р.";
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
}
});
});
}
dataUrls();
});
The task is:
Take prices from another page and replace price on this page
The problem is
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
It's not work.
Replace this line:
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
With:
$('#'+ids[i] + ' .scenePrice').text(newTotalPriceToString));
I guess you are just passing the string of id but not # along with it.
try to find out why is problematic line not working:
alert(ids[i] + ' .scenePrice'); //check whether your selector is correct
alert($(ids[i] + ' .scenePrice').length); //check whether jQuery matched element
But from the look at your code, you are probably just missing '#' in front of id.