1

I'm having problems with some javascript code that I can't seem to figure out. The function I use is

var tagline = new function(){
    document.write(
        tags[
            Math.floor(Math.random()*10)
        ]
    );
};

which calls on an array of 10 strings called "tags" and displays a random entry from that array.

The problem is that for some reason the function executes even when it isn't called, and when I do call it nothing happens. The function just puts the text in the top left corner and does nothing different whether it is or isn't called. This is especially a problem with the styling, because no matter what I do I can't change the position, size, etc. of the text.

(Yes, I'm aware I can do the same thing with

document.getElementById("tag").innerHTML = tags[Math.floor(Math.random()*10)] ;

but I like to write my own functions.)

Thank you for any help you can give!

1
  • 3
    It is because of the new keyword, it shouldn't be there Commented Jun 25, 2014 at 18:39

1 Answer 1

9

It's because you use the new keyword. Remove that so it becomes:

var tagline = function(){

By using the new keyword, you are instantiating a new object from the function, which immediately calls it, and your variable then contains the object, not the function, which explains why you can't call it after it first executes.

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

2 Comments

Thank you! That fixed the problem I was having, but now when I call the function nothing happens. My HTML looks something like <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="templateScript.js"></script> </head> <body> <p id="tag" onload="tagline();"></p> </body>
Don't use onload on a p tag. Use window.onload instead.

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.