0

Hello I'm trying to change a word after each 3 seconds.

The Script:

<script type="text/javascript">
    var text = ["Fysioterapeut", "Kiropraktor", "Praktiserende læge"];
    var counter = 0;
    var elem = document.getElementById("changeText");
    setInterval(change, 3000);
    function change() {
     elem.innerHTML = text[counter];
        counter++;
        if(counter >= text.length) { counter = 0; }
    }
</script>

The PHP/HTMl

$title =  "FIND DEN RIGTIGE <span id='changeText'>Fysioterapeut</span> i dag";

The console says elem is NULL ? Why is that?

The script is running clearly but the text is not changing. Anybody know why?

Troels Johannesen
  • 725
  • 2
  • 7
  • 30

2 Answers2

2

here here actually what happens is your java-script loads first, but at that time it checks for the html element and which will not be available at that time.

so the javascrpt code should be below the php code you have specified.

Lets the sample code should be as like below.

<html>
<head>

</head>
<body>

<?php 
echo "FIND DEN RIGTIGE <span id='changeText'>Fysioterapeut</span> i dag"; 
?>

<script type="text/javascript">
    var text = ["Fysioterapeut", "Kiropraktor", "Praktiserende læge"];
    var counter = 0;
    var elem = document.getElementById("changeText");
    setInterval(change, 1000);
    function change() {
     elem.innerHTML = text[counter];
        counter++;
        if(counter >= text.length) { counter = 0; }
    }
</script>

</body>
</html>

Now it will work . Because now the javascript can find the html elament.

0

The text inside your span is not changing becuse, it is beging declared everytime when change() is being called!

Here is the Solution: WORKING DEMO

$( document ).ready(function() {
    setInterval(change, 3000);
});
var counter = 0;
function change() {
    var text = ["Fysioterapeut", "Kiropraktor", "Praktiserende læge"];
    var elem = document.getElementById("changeText");
    elem.innerHTML = text[counter];
    counter++;
    if(counter >= text.length) { counter = 0; }
}
Vikrant
  • 4,920
  • 17
  • 48
  • 72