I am working on one JavaScript project, where I need to toggle between Celsius and Fahrenheit.
The HTML is here
<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>
And here is the JavaScript Function
this.toggleCF = function() {
console.log('click');
var fahrenheit = document.getElementById('toggleFahrenheit');
var celsius = document.getElementById('toggleCelsius');
if (fahrenheit.style.display === 'none') {
fahrenheit.style.display = 'block';
celsius.style.display = 'none';
} else {
fahrenheit.style.display = 'none';
celsius.style.display = 'block';
}
}
The CSS I used is given
.temperature-celsius {
}
.temperature-fahrenheit {
display: none;
}
If you want to check this application live here is the link
Please click on this link to see app in running form
If you visit the above link and check, you will find that on first click the toggle didn't work. But when you click the second time then it starts working normally.
When the app is first loaded, both the toggleFahrenheit and toggleCelsius divs have no style attribute. They are getting display rules from the CSS, true, but they have no style on themselves.
So think about what your code sees, then. fahrenheit.style.display is null because that block doesn't have the style attribute yet. Therefore, fahrenheit.style.display === 'none' evaluates to false. As a result, the else block is executed and you end up displaying Celsius. Unfortunately, this is the default block which is shown, so the first click doesn't do anything.
The second click works because after the code executes once, now both div blocks have a style attribute.
To fix this, you should either put default style attributes onto the div tags or flip the logic in the code so you check on the Celsius block first, since that's the default display.
Personally, I would use classes to toggle display behaviour instead.
function toggle() {
var fahrenheit = document.getElementById("fahrenheit");
var celsius = document.getElementById("celsius");
fahrenheit.classList.toggle('hide');
celsius.classList.toggle('hide');
}
.hide { display: none; }
<div id="fahrenheit" class="hide">-40 F</div>
<div id="celsius">-40 C</div>
<button onclick="toggle()">Toggle</button>
And yes, I use -40 degrees in the example because I'm lazy and I happen to know this is the same temperature in both systems (:
It does not work because this if (fahrenheit.style.display === 'none') will return NULL as there is no inline style on the element. this method won't "look" at CSS, it only works for inline styles. You could try this:
var element = document.getElementById('toggleFahrenheit'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
to check the CSS properties in pure JS or you could use JQuery which would solve it in one line of code.
This often happen most of the time on your css content not being been loaded up fully i have my issue solved with the following code:
function yourFunction() {
document.addEventListener("DOMContentLoaded", function(){
// you works start here
});
}
The simple solution is to use the EventListener .
I had the same problem with the onclick but when using :
const myEl = document.getElementById('myBtn');
myEl.addEventListener('click', function () {
//Your code here
});
It works on first click!
Related
i found a very simple javascript function for a slideshow (here).
It works perfectly, but i want to change something about the control buttons. Right now, the play/pause button displays it's own name, like this:
<button class="controls" id="pause">Pause</button>
The javascript is set to run a function called pauseSlideshow under certain circumstances which not only pauses/resumes the slideshow, but also changes the displayed content of the button from "pause" to "play":
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.innerHTML = 'Play';
playing = false;
clearInterval(slideInterval);
}
now, what i want to do is to leave the button empty and work width background images, and to do that i planned to do a simple class swap whenever the pauseSlideshow function is triggered. So, first i added a class called pause to the button with the desired background image set in the style:
<button class="controls pause" id="pause"></button>
and next i was going to do something like this:
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.removeClass('pause');
pauseButton.addClass('play');
playing = false;
clearInterval(slideInterval);
}
(where play is another class with a different background image). Sufficient to say, as soon as pauseSlideshow runs, the function crashes. I'm writing something wrong or in the wrong place, but i know that the approach is viable.
please, can anybody point out the error?
EDIT:
Use $(pauseButton).removeClass('pause'); and
$(pauseButton).addClass('play');. addClass and removeCalss are jQuery
methods. And you need to add jQuery reference too. – user3698428
document.getElementById("pause") does not return a jQuery element.
.removeClass() and .addClass() are jQuery functions. So basically you
are trying to call jQuery functions on a non-jQuery element and it's
throwing an error. Change it to var pauseButton = $("#pause"); or
$(pauseButton).removeClass(...); $(pauseButton).addClass(...);
when i try either way, console returns: Uncaught ReferenceError: $ is not defined
When working in pure javascript, you should use this to add or remove class:
pauseButton.classList.remove('pause');
pauseButton.classList.add('play');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
I have a dropdown list that I am hiding on initialization since it's not needed unless the client actually selections a specific radiobuttonlist object. I'm presently setting it to false through
dlInterval.Attributes.CssStyle[HtmlTextWriterStyle.Visibility] = "hidden";
However, attempting to change this through javascript on selection, is failing, at present, I have my code set up to execute as such.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%=rblVectorChoices.ClientID%>").click(function() {
var intVectorSelectedIndex = $('#<%=rblVectorChoices.ClientID %> input[type=radio]:checked').val();
$("#<%=dlInterval.ClientID %>").style.visibility="visible";
if (intVectorSelectedIndex == 1) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
});
</script>
As you can see I'm currently attempting to change the visibility from hidden, back to visible, yet I am receiving an error in the browser console 'TypeError: Cannot set property 'visibility' of undefined'
This doesn't make much sense to me, as the field should be hidden, and not just null. What is causing this to happen, and what is a good solution for such a thing?
The HTML attribute is not called visibility.
In CSS the corresponding attribute for .show() / .hide() is display.
the code you were looking for is :
dlInterval.Attributes.CssStyle["display"] = "none";
or you can just change the javascript to look like, I personally would think that you should hide the element in javascript if your going to show it in javascript . Instead of setting the display:none; in .Net code that is going to disappear when the page is rendered
just re-write your code like this:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
// hide element initially
$("#<%=dlInterval.ClientID%>").hide();
$("#<%=rblVectorChoices.ClientID%>").click(function() {
// much easier way to check if check box is checked
if ( $("#<%=rblVectorChoices.ClientID input[type=radio]:checked%>").is(":checked)) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
});
</script>
also , I strongly , strongly reccomend using classes to select your html elements with javascript or jquery , .Net mangles the id's and you have to write out this weird syntax to get the proper id, uses classes prevents all that
NOTE: if you're going to use this second example then you never need to mess with
dlInterval.Attributes.CssStyle["display"] = "none";
Can you use prop and compare if it's true or false? Also, you cant call $("#<%=dlInterval.ClientID %>").style.visibility="visible"; you have to call it this way:
For those of you reminiscing on the missing .NET inline ID's here's my modified code:
$(document).ready(function () {
$("#<%=rblVectorChoices.ClientID%>").click(function () {
var intVectorSelectedIndex = $('#<%=rblVectorChoices.ClientID%>').prop('checked');
$("#<%=dlInterval.ClientID%>").css('visibility', 'visible');
if (intVectorSelectedIndex == true) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
I have made a small javascript to hide dividers when the value of a dropdown menu has changed.
But for some reason the script doesn't work on my own site.
document.getElementById("type").onchange = function () {
var v = this.options[this.selectedIndex].value;
if (v == 1) {
document.getElementById("CostDiv").style.display = "block";
} else {
document.getElementById("CostDiv").style.display = "none";
}
}
Here's a link: http://jsfiddle.net/WeHv3/
is there more than one element in the html document called CostDiv ?
Please give us the source of the html document as that is only difference at the moment I can see.
I think problem is your listener are unable to attach with your element.
Just add your JavaScript at the bottom of page and your problem is solved.
I have an ASP button in a div to the right side of a page. I want to change the position to the left in the same row dynamically with onchange event of a dropdown.
I did this way:
document.getElementById('divButtonGo').style.Paddingleft="80px"
How do I do this with Javascript?
The example you have provided already is javascript. If you want to change what triggers the code to run, change where you place it.
from an onchange event, into a function in a script tag that is called by something else.
example
<input type="button" onclick="movediv()" />
<script>
function movediv(){
document.getElementById('divButtonGo').style.Paddingleft="80px"
}
</script>
There's several things wrong here. In order of increasing importance:
You're missing the closing slash from your i tag.
I don't see a "divButtonGo" in your html. If it's not there at all, obviously it won't work. If it is, include it in your code snippet.
I'm pretty sure to set the style you're going to need elem.style.paddingLeft, not elem.style.Paddingleft
Your script isn't wrapped inside <script> tags. All Javascript has to be wrapped in these tags, and, in order for that code to operate sucessfully, it's going to have to be placed after the "divButtonGo", or you'll have to wire up an onload event, like window.onload = function() { /* Bombs away! */ };
Your final result should look something like...
<div id="divButtonGo">
My Awesome Content
</div>
<script type="text/javascript">
var el = document.getElementById("divButtonGo");
el.style.paddingLeft = "30px";
</script>
Also, to note, padding wont' exactly change the position of the div, only the position of the content inside. If you want to change the position of the div, use margin-left (in JS, element.style.marginLeft, i believe)
EDIT:
I forgot you wanted it in the onchange event of a dropdown; so you'd do somethign like:
var dropdown = document.getElementById("MyDropDown");
dropdown.onchange = function() {
var el = document.getElementById("divButtonGo");
el.style.paddingLeft = "30px";
};
So, I have this between my head tags
<script type="text/javascript">
hidden_links = document.getElementsByName("javascript_needed");
for (i = 0; i < hidden_links.length; i++) {
hidden_links[i].style.display = "visible";
}
</script>
And my divs are all similar to
<div name="javascript_needed" style="display: none;">stuff</div>
the overall goal here, is to have these divs hide when javascript is disabled, and re-enable them when javascript is enabled.... but for whatever reason, my code doesn't work. I ever tried it in the webkit console, and nothing errored =\
The JavaScript is executed before the divs are in the DOM. The standard way to do something after the DOM is ready is to use jQuery's $(document).ready(function () { });, but there are other ways as well.
The oldschool way is to use <body onload="myfunction()">.
Here's a newer way (edit: put display:none into CSS):
HTML:
<p class='javascript_needed'>hello</p>
CSS:
.javascript_needed {display:none;}
JavaScript:
$(document).ready(function () {
$('.javascript_needed').show();
});
Your JS should be setting the div's display to "block" ("visible" isn't a valid value for display).
Also, from the looks of things your elements aren't in the DOM at the time the code is fired (your code doesn't see them yet). Do any of the following:
Place your code anywhere in the document body below the divs
or, use an unobtrusive strategy to fire your function on window load, a la:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
or, Use a JS framework's "ready" functionality, a la jQuery's:
$(function () {
nameOfSomeFunctionToRunOnPageLoad();
});
"visible" is not a valid value for "display". You're after "inline" or "block".
"visible" and "hidden" are valid values for the "visibility" CSS property.
Difference between display and visible:
An element that is visible still takes up space on the page. The adjacent content is not rearranged when the element is toggled between visible and hidden.
An element that is display=none will not take up any space on the page. Other display values will cause the element to take up space. For example, display=block not only displays the element, but adds line breaks before and after it.
The disadvantage of showing elements on ready is that they will only flicker in after the page has finished loading. This usually looks odd.
Here's what I usually do. In a script in the <head> of the document (which runs before the body begins to render), do this:
document.documentElement.className = "JS";
Then, any CSS selectors that descend from .JS will only match if JavaScript is enabled. Let's say you give your links a class of javascriptNeeded (a class is more appropriate than a name here). Add this to your CSS:
.javascriptNeeded{
display: none;
}
.JS .javascriptNeeded{
display: inline;
}
…and the elements will be there from the start, but only if JavaScript is enabled.