0

Background: I am building a Wordpress site with Elementor and will like to use Javascript to amend the hover properties.

What I have done: Based on the answer in this solution (Change :hover CSS properties with JavaScript), I have been able to get my code to work in JSfiddle (https://jsfiddle.net/lindychen/hL60waqd/2/).

The problem: However, when I import this code into my Wordpress site in the following manner, the code does not have any effect on my page. This is how I implement the code in Wordpress.

<script type="text/javascript">
if (localStorage.getItem('trackerxyz') === 'page_m') {
var css = 'button.elementor-button.elementor-size-sm:hover{ background-color: #cc3633; color: #ffffff } button.elementor-button.elementor-size-sm {background-color: rgba(204,54,51,0.86); #ffffff}';
var style = document.createElement('style');
 if (style.styleSheet) {
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);
}
</script>

Can someone please let me know how to resolve this? Thanks.

  • What is `if (style.styleSheet)` for? – tom Nov 10 '19 at 15:25
  • Are you sure `if (localStorage.getItem('trackerxyz') === 'page_m')` is not the problem? Just add an `alert` inside the `if` statement and see if it's working. – Payam Mohammadi Nov 10 '19 at 15:28
  • 1
    Check if you need a css selector with a higher specificity. If the element is already styled by some other css rule and its selector has a higher specificity your styles will not override the existing styles, [see here for more details](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) – Patrick Evans Nov 10 '19 at 15:35
  • @PayamMohammadi I have several other functions that run using the same `if (localStorage.getItem('trackerxyz') === 'page_m')` and they are working. Also, when I look at the chrome developer console, I do not see any error messages. – sabotenramen1 Nov 10 '19 at 15:57
  • @PatrickEvans Thank you, Sir. You got it right. Inserting !important solved the problem. – sabotenramen1 Nov 10 '19 at 16:08

1 Answers1

0

You can solve this just by this:

if (localStorage.getItem('trackerxyz') === 'page_m') {

  var style = '<style>button.elementor-button.elementor-size-sm:hover{ background-color: #cc3633; color: #ffffff } button.elementor-button.elementor-size-sm {background-color: rgba(204,54,51,0.86); #ffffff}</style>';

  document.head.insertAdjacentHTML('beforeend', style);

}

So no need to create nodes. See insertAdjacentHTML on MDN

tom
  • 9,550
  • 6
  • 30
  • 49
  • This works thank you! The problem was with what @PatrickEvants said, it was a specificity issue. Adding a !important made it work. – sabotenramen1 Nov 10 '19 at 16:08