LeFizzy LeFizzy - 4 months ago 25
Javascript Question

Javascript/Html/Css Random background-image & Word from two javascript array

Welcome to the forums!
Today I wanted to code a bit in language Javascript/html/css/php but I stuck in a problem.
(I have searched for this problem everywhere,but no results.)

My problem is => I have two array in my js file. The first store the pictures from the directory,and the second one is store the words that I want to select randomly by Math() number #indexes
You can read everything in my codes. I have commented them.



window.onload = chooseGame;

var cGamePic = new Array("football.jpg","baseball.jpg");
var cGameName = new Array("football","baseball");
function chooseGame;
var rnd_num = Math.floor(Math.random() * cGamePic.length);
document.getElementById("comp1Game").src = cGamePic(rnd_num);
document.getElementById("??").?? = cGameName(rnd_num);

<!DOCTYPE html>
<html>
<head>
<title>Random pics</title>
<script src="rnd.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container1">
<h1>Some text 1</h1>
<!--The next line will be displayed,but not randomly.
And I want it to the left-side of screen,as background image.
Like: the text "Some text 1" will be displayed in the random selected image.
(The some text 1 is selected randomly too,as "football")
-->
<img src="res/images/football.jpg" id="comp1Game" alt="Compare1">
</div>

<div id="container2">
<h1>Some text 2</h1>
<!-- The future container to see the 2nd selected image & word in it (right side of screen)
Like,if js select number 6,the word and image will be "baseball" and "baseball.jpg"
Shortly,I want to do it.
-->
</div>
</body>
</html>




Answer

Easier with jQuery:

<!DOCTYPE html>
<html>
    <head>
        <title>Random pics</title>
        <script src="rnd.js"></script>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script> 
    var cGamePic = new Array("football.jpg","baseball.jpg");

    $( document ).ready(function() {
        chooseGame();
    });

    function chooseGame(){
        var pic = cGamePic[Math.floor(Math.random()*cGamePic.length)];
        var name = pic.replace(/^.*[\\\/]/, '');

        $("#comp1Game").attr("src",pic);
        $("#container1 h1").html(name);
    }
</script> 

    </head>
    <body>
        <div id="container1">
            <h1>Some text 1</h1>
            <img src="res/images/football.jpg" id="comp1Game" alt="Compare1">
        </div>
    </body>
</html>