yukashima huksay
yukashima huksay

Reputation: 6238

console not working and function starts working late

It's like javascript doesn't respect the style definitions in the css and only respects the changes made in css by javascript itself:

<body onload="fader()">

    <img id="ssio" src="../images/slideshow/1.jpg" alt="slideshow" style="width:100%;height:80%;" />
    <img id="ssie" src="../images/slideshow/2.jpg" alt="slideshow" style="width:100%;height:80%;" />

<!--css work-->

<style>

img#ssio{
    transition:opacity 1s;
    position:absolute;
    opacity:1;
    margin:0;
    padding:0;
}
img#ssie{
    transition:opacity 1s;
    opacity:0;
    margin:0;
    padding:0;
}

</style>

<!--js work-->

<script>

function fader() {
    console.log(document.getElementById("ssio").style.opacity, document.getElementById("ssie").style.opacity, ",", ssion, ssien)
    document.getElementById("ssio").style.opacity = document.getElementById("ssie").style.opacity;
    document.getElementById("ssie").style.opacity = 1 - document.getElementById("ssio").style.opacity;
    setTimeout(fader, 4000);
}

</script>
</body>

Why doesn't it work as expected? Why do console and js treat the defined opacity in css as null? How can I fix it?

Upvotes: 2

Views: 59

Answers (1)

Matrix
Matrix

Reputation: 98

There are some problems in your function:

First, you forgot to define what are variables ssion and ssien which is why there is no log written in console.

The second problem is that JavaScript doesn't look at the properties in the stylesheet(however it looks at the properties in the in-line style). So since initially when the document loads, you haven't defined opacity in the in-line style, thus document.getElementById("ssie").style.opacity has no value which means after the first run of your function you'll end up setting opacity of ssie to 1.

You can read the answer of the topic How do I get the opacity of an element using Javascript? for further information about how you might fix this.

However, in my opinion the correct way of doing this is actually using display or visibility CSS properties. you might want to look them up.

Upvotes: 2

Related Questions