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.
Related
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!
I want to hide a spinner div once ALL elements are loaded and in position on my page. I put a fadeOut() function on my spinner div in the window.on('load', ..., but I can see the tab/page is still loading even though the elements/assets are not in the correct css position yet. How do I force the spinner div to remain until everything is in place, i.e. until the loading icon on the tab is finished spinning?
This is my code:
$(window).load(function() {
$('#spinner').fadeOut();
}
jQuery(document).ready(function($){
// Append the spinner div.
$("#spinner").append(spinner.el);
}
It sounds like you have a large volume of CSS and it is taking a long time for the browser to compute the style for each element after all content for the page has loaded. You could do some experiments using your timeout idea, and polling one or more elements on the page to see when the computed style matches the expected style. The last element to be assigned a computed style might vary at each page load, and/or by browser, so you would definitely need to test your method. The example below uses some information from the accepted answer here to poll an element for an expected style.
var expectedTop="5px";
function ready() {
$('#spinner').fadeOut();
}
function poll() {
var o = document.getElementById("pollElementId");
var comp = o.currentStyle || getComputedStyle(o,null);
if(comp.top==expectedTop) {
ready();
}
else {
setTimeout("poll()",500);
}
}
jQuery(document).ready(function($){
$("#spinner").append(spinner.el);
poll();
}
Here pollElementId is the id of an element in the DOM that we are positioning via CSS.
I want to achieve a sticky menu like the left navigation on this page: http://getbootstrap.com/2.3.2/scaffolding.html.
My menu is a nav element with position:relative (I tried static as well) that goes fixed when it reaches the top of the viewport.
here's my function:
$(document).ready(function() {
function stickyNav() {
var elementPosition = $('nav').offset();
console.log(elementPosition);
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('nav').addClass("sticky");
} else {
$('nav').removeClass("sticky");
}
});
}
stickyNav();
}); //document ready
the console.log(elementPosition); returns an offset top of around 1200px on page load, which is wrong. But if i resize the page, the value changes to around 650px which is the correct offset top and the function does what it is supposed to be doing.
I've looked around and found out that offsetp top maybe wrong when it's on hidden elements, or it has issues with margins but I actually don't have any complex structure here, just a single visible nav element .
any help on figuring this out would be much appreciated! thanks!!
jQuery(document).ready handler occurs when the DOM is ready. Not when the page is fully rendered.
https://api.jquery.com/ready/
When using scripts that rely on the value of CSS style properties,
it's important to reference external stylesheets or embed style
elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
So if you're using stylesheets that are loaded AFTER the script in question, or the layout of the page depends on image sizes, or other content, the ready event will be hit when the page is not in its final rendering state.
You can fix that by:
Making sure you include all stylesheets before the script
Making sure the CSS is more robust, and doesn't depend that much on content size (such as images)
Or, you can do this on window load event.
Edit:
If you want to make your script dependent on more than one async event (like the loadCSS library), use this:
var docReady = jQuery.Deferred();
var stylesheet = loadCSS( "path/to/mystylesheet.css" );
var cssReady = jQuery.Deferred();
onloadCSS( stylesheet, function() {
cssReady.resolve();
});
jQuery(document).ready(function($) {
docReady.resolve($);
});
jQuery.when(docReady, cssReady).then(function($) {
//define stickyNav
stickyNav();
});
You can add a check to see if your CSS has loaded by setting a style tag in your document which shows a test element, and then overwrite this in your CSS file to hide it. Then you can check the status of your page by checking this element. For example...
In your HTML:
<div id="loaded-check" style="display:block; height:10px; width:10px; position:fixed;"></div>
In your CSS:
#loaded-check { display:none; }
In your jQuery script:
var startUp = function() {
var cssLoaded = $('#loaded-check').is(':visible');
if (cssLoaded) {
$('#loaded-check').remove();
doOtherStuff()
}
else {
setTimeout(function() {
startUp();
}, 10);
}
}
var doOtherStuff = function () {
//bind your sticky menu and any other functions reliant on DOM load here
}
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 a div which is hidden initially and will be visible later depending on some click events results.
I have wrote this
$(document).ready(function () {
$('#<%=disable.ClientID %>').hide();
});
<div id="disable" runat="server">The following question is disabled</div>
But when i disable CSS it appears, when i don't disable css it gets invisible. how do i make this invisible even when css is disabled and visible later again
There is no way to make something invisible without CSS. But you can remove it:
$(document).ready(function () {
$('#<%=disable.ClientID %>').remove();
});
You would then need to readd all the mark up again should you wish to show it again.
Edit
You could do something like this:
$(document).ready(function () {
var item = $('#<%=disable.ClientID %>');
$(document).data('myElement', item.clone());
item.remove();
});
then you could re-add it
$(document).append($(document).data('myElement'));
If you are willing to write server code for this, then you could do this in the code-behind.
// c#
if(some condition...)
{
disable.Visible = false;
}
This will remove the div from the HTML output of the page.
I do not get you when talking about enabling and disabling css, but you can always manage the DOM elements via DOM manipulation. As you tagged jQuery:
$(document).ready(function () {
/* please try top avoid mix server side variables and javascript code */
$('#myTargetDiv').hide();
$('#myToggleButton').on('click',function(){
/* select the elements you want to hide / show with the click on this element */
var $elements = $('#myTargetDiv');
$elements.toggle();
});
});