Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
Applying CSS class to a Javascript

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!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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 class="side-img" src="'+myimages[ry]+'" border=0>')
about 4 years ago · Juan Pablo Isaza Relatório

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda