2

So the idea is this. I have an array in the js file as well as a function that refers to a random element from that array. I want to be able to click a button and the text in the span changes to a random element in the array. I already have a way of doing this. I have a span with an id of "change_equivalently". Then in the javascript file, I have

var Equivalentlys = [
"Equivalently, ",
"Alternatively, ",
"Another way of saying this is that "
];

$('#shuffle').click(function() {
    var length = (Equivalentlys.length + 1);

    var x = Math.floor(Math.random()*length);

function Equivalently(i){
    return Equivalentlys[i];
};

$('#change_equivalently').text(Equivalently(x));

});

My question is that when I write out the html code, I always have to write

<span id = "change_equivalently"> ... </span>

in order to be able to change the words up upon clicking the button.

But I want an easier way. I tried something like

  <var> Equivalently( 1 ) </var> 

to see if I could refer to the javascript function, but it didn't work.

How could I go about approaching this?

Dan Dao
  • 31
  • 2

2 Answers2

3

First of all, the approach you're currently using is better than what you want--it separates presentation from function and is widely regarded as the best practice.

However, you can (but, as I said, probably shouldn't) include code to be called when your element is clicked:

<span onclick="doStuff()"> blarg </span>

If you just want to be able to have JavaScript code that turns into HTML (like PHP or similar templating systems), you won't be able to do it with JavaScript.

Ultimately, the best way is just to use a span to mark the content and add a click event in your script, the way you're doing right now. This is the best semantically: in the html, all you say is that that particular word/position is changeable; you specify how it changes in your code.

Tikhon Jelvis
  • 64,915
  • 16
  • 168
  • 210
  • Surely `document.write` (http://javascript.about.com/library/blwrite.htm) will allow you to have Javascript that turns into HTML like php? Though +1 for saying that you shouldn't do it this way anyway. :) – Chris Jan 12 '12 at 09:55
  • 1
    [Why is document.write considered a 'bad practice'?](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Didier Ghys Jan 12 '12 at 09:58
  • Ah ok. Well, I don't know any php, so I'll just stick to what I did originally. It's just gonna be a pain to continue putting spans everywhere with it's id. But I guess it's not that bad. – Dan Dao Jan 12 '12 at 10:25
  • Php wouldn't help you in this case; I was just bringing it up as an example of a language that had a template mechanism that allows you to output html directly from the code. – Tikhon Jelvis Jan 12 '12 at 10:27
1

Do you mean this?

<script type="text/javascript">
  Equivalently(1)
</script>
YuS
  • 1,940
  • 1
  • 12
  • 21