Paweł Skaba
Paweł Skaba

Reputation: 681

jquery function works only once

I dont have brightest idea why this function works only once.. Any ideas?

var ColorsTable = ['red', 'green', 'blue', 'gold', 'white', 'black'];
var Rand = ColorsTable[Math.floor(Math.random() * ColorsTable.length)];
var Rand2 = ColorsTable[Math.floor(Math.random() * ColorsTable.length)];

jQuery( document ).ready(function( $ ) {
    $('.losuj').click(function () {
        $("#rama").css("background", Rand);
        $("#rama2").css("background", Rand2);
                var input = $('#wpis');
                input.val('')
                input.val(input.val() + Rand);
                var input2 = $('#wpis2');
                input2.val('')
                input2.val(input2.val() + Rand2);
    }); });

http://jsfiddle.net/U6MFp/5/

Upvotes: 0

Views: 123

Answers (2)

Andrew
Andrew

Reputation: 5083

I'm assuming you're expecting a different color each time? If that's the case, you're only generating the random colors once when your document loads and using the same values each time.

Try moving the top code inside the function definition like this:

var colorsTable = ['red', 'green', 'blue', 'gold', 'white', 'black'];

$(document).ready(function() {
    $('.losuj').click(function () {
       var rand = colorsTable[Math.floor(Math.random() * colorsTable.length)];
       var rand2 = colorsTable[Math.floor(Math.random() * colorsTable.length)];

       $("#rama").css("background", rand);
       $("#rama2").css("background", rand2);
       $('#wpis').val(input.val() + rand);
       $('#wpis2').val(input2.val() + rand2);
    }); 
});

Upvotes: 1

adeneo
adeneo

Reputation: 318172

The random colors are only calculated once at pageload, move that inside the click handler

var ColorsTable = ['red', 'green', 'blue', 'gold', 'white', 'black'];


jQuery(document).ready(function ($) {
    $('.losuj').click(function () {
        var Rand = ColorsTable[Math.floor(Math.random() * ColorsTable.length)];
        var Rand2 = ColorsTable[Math.floor(Math.random() * ColorsTable.length)];
        $("#rama").css("background", Rand);
        $("#rama2").css("background", Rand2);
        var input = $('#wpis');
        input.val('')
        input.val(input.val() + Rand);
        var input2 = $('#wpis2');
        input2.val('')
        input2.val(input2.val() + Rand2);
    });
});

FIDDLE

Upvotes: 3

Related Questions