javascript not working locally but works in jsfiddle [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
I have very simple code
html
<div id="ball" class="ball"></div>
css
#ball{
width: 20px;
height: 20px;
border-radius: 100%;
background: #0f0;
position: absolute;
bottom: 150px;
left: 350px;
}
javascript
<script type="text/javascript">
document.getElementById('ball').style.backgroundColor="red";
</script>
I tried this code in jsfiddle and it works but why this is not working locally? I tried changing to , but I've no idea why this is not working. It's showing the error:
TypeError: document.getElementById(...) is null

As mentioned in the comment, your initialization order is messed up. You can use window.onload to fix it:
<script type="text/javascript">
window.onload = function() {
document.getElementById('ball').style.backgroundColor="red";
};
</script>
Note also that you can only have one onload trigger function. Here are some ideas on how to support multiple trigger functions. The easiest, is of course, to just use JQuery's ready function.
Another way is to put the <script> tag into the body after the DOM element(s) that it depends on. This is often encouraged for performance reasons, but it tends to make things less readable.
The reason as to why <script> tags in the head are executed in sequence (instead of delaying execution until after the DOM has loaded) is: Performance. For example, you sometimes might want to start asynchronous requests before the document has finished loading. If you are not concerned about performance, it's safer to execute them "onload".
Ultimately, there are a lot of considerations to be made when placing your <script> tag. If you want to learn more, this might be a good starting point.
About the second part of your question: The reason as to why it works in JSFiddle is that, by default, it executes scripts onload. You can reproduce the bug on JSfiddle by choosing "no wrap - in head": http://jsfiddle.net/aDuwg/.

Related

CSS visual rendering not showing until JS script has finished

I have a JS function which is triggered on a click event.
At the very first line in the function, I add a class to a html element. The html is a custom loader, and the class just makes the loader visible.
The problem is that the loader does not appear until the script has actually finished executing. The class is set on the element right after the script starts, but nothing visually happens in my browser until the script has finished executing.
$('body').on('click', '#button', function(){
$('#loader').addClass('active');
$('.fields').each(function(i, el){
// does some intensive stuff, including appending elements to a dom fragment, triggering events programmatically. This takes 5-10s to execute.
});
// the loader only appears visible in the browser once the code executed in the loop finishes.
});
The CSS in the active class is:
.active{
z-index: 9999;
display: block;
position: absolute;
left: 40%;
left: calc(50% - 18px);
left: -webkit-calc(50% - 18px);
top: 40%;
}
I tried do re-search this issue, but I couldn't find anything on google.
Maybe it's because I do not know what keywords I should search, I am not sure what is causing or how to refer to this issue.
So guys, you are my last hope. Could you point me in the right direction on how to debug or what is causing this?
If I add the fields loop inside a setTimeout function with 0 timeout, it works. But the idea is to fix it the correct way, and understand why it's not working as expected.
If I add the fields loop inside a setTimeout function with 0 timeout, it works.
This is a sensible approach, although requestAnimationFrame is stylistically slightly nicer.
But the idea is to fix it the correct way, and understand why it's not working as expected.
The browser won't trigger a repaint until the function has finished running - otherwise, it would do a repaint for every individual DOM modification, which would be expensive.

Change html Text with conditional css but without js

Sorry about this absolutely newbie question, but I've been searching for an already similar post, and couldn't find it.
My question is:
I have a paragraph text in my HTML code which I want to automatically change into a new text once I click a specific Button.
Can this be done with CSS only, without any javascript?
Since some users block javascript, that's why I was looking for a way around...
Thanks a lot.
actually #Vaidya & #Preet it is possible via css only :
https://css-tricks.com/swapping-out-text-five-different-ways/
#fana you'll need to use a plus selector or tilde selector to make the changes affect the following div not itself but other than that you're good to go.
I can see that using css to replace content is strongly discouraged within the stackoverflow community. However I haven't found another cause other then that of code cleanliness.
I really think in coming years the true potential of CSS/SASS will unravel and people will cease to see the programmatic/dynamic as strictly excluded from CSS/SASS.
It can't be done through CSS You must need to add a script for an on-click event.
I know it is not what you exactly want but it can give you idea about it and with some changes you can make it.(but conditional and on click event using css is definitely not possible, you need javascript for that)
If you can make it work on Text click itself then it is easily possible. You only need a checkbox which is hidden and label in which you will show text. On click of text you can swap into anther text with only css:
#example {
position: relative;
}
#example-checkbox {
display: none;
}
#example-checkbox:checked + #example:after {
content: "Hide";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: white;
}
<input id="example-checkbox" type="checkbox">
<label for="example-checkbox" id="example">Show</label>
Reference See css only part.
Hope it will help you.

How to get computed style and the source of this rule? [duplicate]

This question already has answers here:
Find all CSS rules that apply to an element
(10 answers)
Closed 5 years ago.
I want to get the element computed style and the css (file and line) that applies that rule. Similar to what Chrome Dev Tools does when the "Computed" tab is used and you click on that arrow beside the value.
In short, I want to be able to, using javascript, find out these two things:
What is the CSS value that is actually being applied to that element (computed style)
Once I found the computed style, I want to know where it comes from (like file name and line number)
I know this can be done manually using devtools, but I need this done by a script.
Thanks
You can use Window.getComputedStyle(). An example of usage:
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
See MDN Documentation to learn more how to use this feature and it's compatibility with different browsers.
Unfortunately, this approach will not give you the location of where this value comes from.

Can't see animation when using jQuery animate

so I know this question has been asked many times, but I could not find any answer that works for me. I've already included the jQuery Google API line before my script, and I'm pretty sure my syntax is correct as far as I know (since I'm following a tutorial video for this). I've also added a few lines of console.log() in some places and I know for sure that it is going pass the animate function and reaching the end of the code. Here is my code:
index.html (Not all, just a small part to show that I have the API included)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
javascript.js (Also not all, just the part I'm having problem with)
prepareToAttack = function () {
$("#pikachu-img").animate({
top: "-=25px"
}, 200, function () {
$("#pikachu-img").animate({
top: "+=25px"
}, 200);
});
};
Back to index.html (This is where the pikachu image is set up)
<img id="pikachu-img "src="img/pikachu.png" class="absolute" style="height: 115px; top: 40px; right: 46px">
Does anyone have any idea why I'm not seeing the animation?
Maybe the problem caused by img tag, your double quote of id stick with src.
No other problem found in my test:
NOTE: Using the style attribute in HTML is bad practice. Use plain CSS instead! Remember when an elements CSS in dynamically manipulated say whatever.style.color = "red" it will add the style attribute, then and only then it should be used.
Also thanks to HTML5 you can scrap the type="text/javascript" on your script tag.
HTML:
<img id="pikachu-img" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQtDxj0kmEFUVNCUDF4G6553Hm-1w_ADcyYKhpkQf7pfsusCpHsbYpS3bQm">
CSS:
.pikachu-img {
position: absolute;
height: 115px;
top: 40px;
right: 46px;
}
JS:
$(function() {
$("#pikachu-img").animate({
top: "-=25px"
}, 2000, function() {
$("#pikachu-img").animate({
top: "+=25px"
}, 2000);
});
});

Why does my element move around when the page loads and when javascript executes?

Consider this page: http://www.collegeanswerz.com/adelphi-university/academics/professors/do-professors-explain-things-clearly-are-professors-interesting.
The element in question is "Do they make things easy to understand? Are they interesting?" in the light gray box on the top right. When the page loads, it starts off high up, and then it moves 30px down. The same thing happens when you click "Information" in the navbar.
This is the element: <div id="question_sub" class="well"></div>.
Why does this happen, and how can I fix it?
Answer to Why does it Happen
If you try loading your page without javascript the page looks like
Problem
Your page is very heavily dependent on js for dom elements modification and for styling also.
Solution To avoid this style your page in css as maximum as possible, JS should be used for interaction or making web page attractive.
Probable Problem
If you are loading lots of external script which are not related to page content like discus inside head element
Solution
Move all the external js from head to end of body if you are not doing it, or you can load them asynchronously. Refer Mozilla Synch and Async
Another Way
If you want content to be loaded from server only when some portion of it has changed then use application cache technique with this the pages will be loaded from client machine so only initial page load will take time for the first load and then it will be quite fast
Check Using Application Cache
Other Ways
Compress Javascript and CSS
Use gzip compression
there are lot of more stuff, search it you will find ocean of knowledge, reference
If you want to keep the 50px margin between the elements then change the navbar class to also be 50px
.navbar {
margin-bottom: 50px;
}
Currently it is set at 20px;
Remove this code :-
comments powered by <span class="logo-disqus">Disqus</span>
This is a problem about fusion-margin
Remove this:
#college_pages_css .questions {
margin-top: 30px;
And try this, it will work fine:
#college_pages_css .questions {
margin-top: 0;
If you want a margin, put the margin on div#normal ;)
It looks like you're having a CSS issue due to the floating elements.
try floating the nav on the left:
#normal > nav {
float: left;
}
.disqus { float: right }
and wrap the following elements in a div that is floated to the right, for exemple:
<div class="disqus">
<div id="question_sub" class="well">Do they make things easy to understand? Are they interesting?</div>
<p class="stratify" style="display: block;">tip: talk about the best/worst/average cases</p>
<div id="disqus_thread">
</div>

Categories