Home > other >  Applying CSS class to a Javascript
Applying CSS class to a Javascript

Time:12-02

First off I just wanna state that I know next to nothing when it comes to Javascript so forgive me if I use the wrong jargon.

I'm trying to do a layout for tumblr where the sidebar image will change upon refresh. I'm using an existing layout and following another tutorial on how to achieve the effect.

The CSS class for the sidebar is called "side-img".

The CSS from the original layout is as below

<img class="side-img" src="{image:Sidebar Image}">  

From another tutorial, I'm asked to replace it with the following code to get the changing sidebar image working.

<script language="JavaScript">
<!--
 
 
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="IMAGE URL"
myimages[2]="IMAGE URL"
myimages[3]="IMAGE URL"
 
 
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<img src="' myimages[ry] '" border=0>')
}
random_imglink()
//-->
</script>

The sidebar image does change upon refresh but now it also loses all the CSS class style which has been set for it in the original layout (e.g. rounded corner, border width, colour etc).

Seeking advice on this. Thanks!

CodePudding user response:

It's because you are creating a new element with

document.write('<img src="' myimages[ry] '" border=0>')

and that element is missing the css class that gives it styling.

Try

document.write('<img  src="' myimages[ry] '" border=0>')

CodePudding user response:

Multiple issues but

<script language="JavaScript">

Isn't valid, there is no language attribute for <script> tags.

Well there is, but it's deprecated.

var myimages=new Array()

It's not recommended to create an array like this, it's preferred to use:

var images = []

If you want to randomly change the src attribute of an image, here's the way to do it:

<img class="side-img" id="random-image">  

<script>
var images = ["1.png", "2.png"]
var index = Math.floor(Math.random() * images.length)

document.querySelector("#random-image").src = images[index]
</script>
  • Related