Fabian Schneider
Fabian Schneider

Reputation: 809

What is wrong with my HTML-Javascript-connection?

I am having some trouble with my website: When the website finished loading in the browser (onload) it should trigger a JavaScript Function called divTimeout1() in an external JavaScript-File

This is my code:

<script src="js/javascript.js"></script>
<body onload="divTimeout1()">
[...]

and my javascript.js file:

function divTimeout1() {
  var div = document.getElementById("info_pic");
  var opacity = div.style.opacity;
  var inter = setInterval( function f (div, opacity) {
    if (parseInt(opacity) > 0) {
      div.style.opacity = (parseInt(div.opacity)-1) + "%" 
    }
    else {
      clearInterval(inter)   
    }
  }, 10)
}

Is my JavaScript-code wrong? Or did I do something wrong with the "embedding" of the Script?

Thanks for your advice in advance...

Upvotes: 0

Views: 112

Answers (2)

The_Black_Smurf
The_Black_Smurf

Reputation: 5269

In those situation, you should always look at the browser's console to see what is the error message (if there's any).

In your particular case, you should take your javascript outside the html and trace from there to see what is going on inside the divTimeout1 function.

window.onload = function() {
  divTimeout1();
}

If you are using JQuery, you should consider using the $(document).ready() instead to make sure the whole html is loaded before trigerring your function:

$(document).ready(function(){
  divTimeout1();
})

Most modern browser have great debugging tools to trace the javascript execution. In chrome, you can press F12 or Ctrl + Shift + I and then put a break point on the line you want to break in.

Upvotes: 1

user663031
user663031

Reputation:

You're doing a half-baked animation which can be easily handled by CSS transitions, avoiding going to all the trouble of having to write JS which seems to be giving you trouble. Try something along these lines:

#info_pic            { transition: opacity 1s; opacity: 0; } 
#info_pic.transition { opacity: 1; }
function startTransition() {
    document.getElementById('info_pic').className = 'transition';
}

document.body.onload = startTransition;

There are too many problems in your original code to go into here. But I doubt if that's relevant since using CSS transitions is so much cleaner.

Upvotes: 0

Related Questions