mercredi 23 mai 2018

display words at random position on click

It's the first time I ever post something on a forum. I'm new with javascript.

I found this : http://jsfiddle.net/6eTcD/2/ You type a word, and submit and then it appears randomly on the page.

HTML :

<form>
    <input type="text">
    <input type="submit">
</form>

JAVASCRIPT

document.querySelector("form").addEventListener("submit", function(e) {
    e.preventDefault();

    var fullWidth = window.innerWidth;
    var fullHeight = window.innerHeight;

    var text = this.querySelector("input[type='text']").value;

    var elem = document.createElement("div");
    elem.textContent = text;
    elem.style.position = "absolute";
    elem.style.left = Math.round(Math.random() * fullWidth) + "px";
    elem.style.top = Math.round(Math.random() * fullHeight) + "px";
    document.body.appendChild(elem);
});

Though I would like to choose myself the words that are gonna be displayed, and I'd like them to appear when the button is clicked. And at random positions. but not randoms words.

I tried to replace "text" with "words" and added

    function getRandomWord() {
  var words = [
    'Hello',
    'No',
    'Hi',
    'Banana',
    'Apple'
  ];

MY MODIFICATIONS :

// A $( document ).ready() block.
$( document ).ready(function() {


document.querySelector("form").addEventListener("submit", function(e) {
    e.preventDefault();

    var fullWidth = window.innerWidth;
    var fullHeight = window.innerHeight;

    function getRandomWord() {
  var words = [
    'Hello',
    'No',
    'Hi',
    'Banana',
    'Apple'
  ];

    var elem = document.createElement("div");
    elem.textContent = words;
    elem.style.position = "absolute";
    elem.style.left = Math.round(Math.random() * fullWidth) + "px";
    elem.style.top = Math.round(Math.random() * fullHeight) + "px";
    document.body.appendChild(elem);
});

    });

Anyway I don't think any of what I did could work. I'm new to this. Would any of you now?
Thank you in advance




Aucun commentaire:

Enregistrer un commentaire