BigCola
BigCola

Reputation: 351

Applying css style to an :after pseudo-element on a javascript call

I have a dropdown div I would need to make slide down when a certain element is clicked, so I wrote a js function and so far it seemed to work. To this certain element I used :before and :after to create an arrow-like figure which I would need to change style to according if the dropdown div is slide down or up.

function opere_slide(){

    ul=document.getElementById('opere');
    opere_tag=document.getElementById('opere_tag');
    margin=ul.style.marginTop;
    if(margin=='0px'){
       ul.style.marginTop='-200px';
       opere_tag.style.backgroundColor='white';
       opere_tag.style.borderBottomColor='#BCD2EE';
    }
    else{
       ul.style.marginTop='0px';
       opere_tag.style.backgroundColor='#F8F8F8';
       opere_tag.style.borderBottomColor='#E0E0E0';
    }
}

That's why I added to the above function a peace that should create an HTML style element and so apply the new css code I was needing. Problem is: function doesn't seem to work anymore.

function opere_slide(){

    head=document.getElementsByTagName('head')[0];
    stylesheet=document.createElement('style');
    ul=document.getElementById('opere');
    opere_tag=document.getElementById('opere_tag');
    margin=ul.style.marginTop;
    if(margin=='0px'){
       ul.style.marginTop='-200px';
       opere_tag.style.backgroundColor='white';
       opere_tag.style.borderBottomColor='#BCD2EE';
    }
    else{
       ul.style.marginTop='0px';
       opere_tag.style.backgroundColor='#F8F8F8';
       opere_tag.style.borderBottomColor='#E0E0E0';
       text=document.createTextNode('div#opere_tag:before{border-top:10px solid #E0E0E0;}
       div#opere_tag:after{border-top:10px solid #F8F8F8;}');
       stylesheet.appendChild(text);
       head.appendChild(stylesheet);
    }
}

P.S.: one last thing might be important.. The function is internal to a php echo function that "echoes" the HTML script element.. That is why I only used single quotes.

Upvotes: 2

Views: 940

Answers (2)

Gavriel
Gavriel

Reputation: 19247

you can try something like:

<div class="???">
 ...
</div>

when you scroll you change the class on the div to scrollDown or scrollUp, and change your css so it has the different arrows on

.scrollUp div#opere_tag:after{...}
.scrollDown div#opere_tag:after{...}

Upvotes: 0

oezi
oezi

Reputation: 51817

theres a syntax-error due to the linebreak in your textnode-string:

text=document.createTextNode('div#opere_tag:before{border-top:10px solid #E0E0E0;}
   div#opere_tag:after{border-top:10px solid #F8F8F8;}');

just remove that linebreak:

text=document.createTextNode('div#opere_tag:before{border-top:10px solid #E0E0E0;} div#opere_tag:after{border-top:10px solid #F8F8F8;}');

for more information, please take a look at "How do I break a string across more than one line of code in JavaScript?" here on SO.

Upvotes: 2

Related Questions