skip to Main Content

I am trying to cycle through all of the Zodiac signs using JavaScript/jQuery.

Is there a way to do this by just counting up and then displaying that character?

At first I tried this using the &#XXXX way of writing the characters, but they would not be converted to their respective Unicode character, but instead displayed literally.

Then I tried using uXXXX but I got the Error: "malformed Unicode character escape sequence". Here is my code:

setInterval(changeZodiac, 200);

var whichZodiac = 9800;

function changeZodiac() {
    var hexZodiac = whichZodiac.toString(16);
    console.log(hexZodiac);
    $("#zodiac").text("u" + hexZodiac);
    whichZodiac++;
    if (whichZodiac > 9811) {
        whichZodiac = 9800;
    }
}

The error feels like it is there to prevent a problem if something like this happens accidentally. But is there a way to make this work intentionally?

2

Answers


  1. Use html() instead of text():

    var whichZodiac = 9800;
    function changeZodiac() {
        $("#zodiac").html("&#" + whichZodiac + ";");
        if (++whichZodiac > 9811) whichZodiac = 9800;
    }
    
    setInterval(changeZodiac, 200);
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="zodiac"></div>
    
    Login or Signup to reply.
  2. Don’t create a string with an escape sequence and then try to parse it. Just use String.fromCharCode to directly get the character:

    var whichZodiac = 9800;
    function changeZodiac() {
        document.getElementById("zodiac").textContent = String.fromCharCode(whichZodiac);
        if (++whichZodiac > 9811) whichZodiac = 9800;
    }
    
    setInterval(changeZodiac, 200);
    <div id="zodiac"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search