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?

4
  • Is this script before element with id changeText or after? It is possible that you are trying to access element before it is in the document. Commented Apr 20, 2015 at 11:22
  • as you have defined elem above the function. Commented Apr 20, 2015 at 11:22
  • So to be clear the script is running after the load of the html. Commented Apr 20, 2015 at 11:22
  • @TroelsJohannesen try to check this answer stackoverflow.com/questions/8739605/… whether there is not your case one of the points Commented Apr 20, 2015 at 11:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.