Good!
I am developing a web page for a personal project, and I have difficulties when I want to add a new function.
The page is simply a table with two cells and a div in each of them. The one on the left is the menu and the one on the right is the information. In the aforementioned div, I try to make the background image change each time I enter, choosing aletoriamente among the 10 backgrounds I have.
The HTML.
<html>
<head>
<title>Prj</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script src="scripts/rd_background.js"></script>
<table border="0" class="master">
<tbody>
<td class="left">
<div class="dleft">
<table border="0" class="slave">
<tbody>
<tr>
<td><img src="images/logo-white.png" alt="PIOCAM 2018" style="width:135px;height:130px;" class="logo"></img></td>
</tr>
<tr>
<td class="tdmenu"></td>
</tr>
</tbody>
</table>
</div>
</td>
<td class="right">
<div class="dright" id="jsBg" >
<script type="text/javascript">randBg();</script>
</div>
</td>
</tbody>
</table>
</body>
The CSS (I only show the CSS with which JavaScript interacts, the rest has nothing to do with the functionality.).
div.dright {
border-radius: 8px;
margin: 2em 2em 2em 2em;
background: url("images/bg/3.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: center;
opacity: 0.5;
height: 91vh;
}
And the JavaScript.
var bgCount = 10;
function randBg() {
var num = Math.ceil( Math.random() * bgCount );
document.getElementById('jsBg').style.background = 'url("images/bg/"+num+".jpg")';
}
I have analyzed all the code based on my knowledge, I have searched in google and I still do not understand the problem.
If someone is so kind as to tell me why the image is not changed randomly and correct the fault, I appreciate it. Thanks in advance.
(Update) Fixed problem , but not entirely.
The cause of the problem was in the javascript code:
Before.
'url("images/bg/"+num+".jpg")';
Afterwards.
'url("images/bg/'+num+'.jpg")';
A simple mistake of quotes. Now the solution has generated a problem: the image does not respect background-size: cover; background-repeat: no-repeat; , or background-position: center ; . The image is automatically positioned without respecting those CSS lines.