-1

As part of a custom WordPress loop I have the following line which calls the post thumbnail as a background via inline CSS. I want the background thumbnail to change on hover.

<div style='background-image: url(<?php echo get_the_post_thumbnail_url(); ?>);'>

Tried to do it with mixing answers I found

How to write a:hover in inline CSS?

https://wordpress.stackexchange.com/questions/220029/how-to-get-the-first-image-gallery-of-a-product-in-woocommerce-in-a-loop

<div onMouseOut="this.style.background-image='url(<?php echo get_the_post_thumbnail_url(); ?>);'" onMouseOver="this.style.background-image='url(<?php global $product; $attachment_ids = $product->get_gallery_attachment_ids(); echo $image_link = wp_get_attachment_url( $attachment_id ); ?>);'">
GibsonFX
  • 1,000
  • 2
  • 10
  • 33
  • 1
    `this.style.background-image` would be a math operation, trying to subtract `image` from `this.style.background` … You need to use either camel case or `["property-name"]` syntax in such a case. – misorude Nov 07 '18 at 10:02
  • Thank you, Okay I get how I would write style.backgroundImage, but I rarely use javascript, how would I write the ["property-name"] Syntax? this.style.["background-image"] like so? – GibsonFX Nov 07 '18 at 10:07
  • 1
    Without the dot, `this.style["background-image"]`, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation – misorude Nov 07 '18 at 10:10
  • Thank you, I'll try that – GibsonFX Nov 07 '18 at 10:13

2 Answers2

1

Could you try:

<div script="this.addEventListener("mouseover", this.style.backgroundImage='url(<?php echo get_the_post_thumbnail_url(); ?>);');>

Then change the event listener to "mouseout" and change the URL link.

0

With the help of Misorude's comments I managed to get the effect I was after. Adding the ["property-name"] syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation and then correcting the positions of other several syntax.

The single quote ' had to go before the semicolon ;

Adding the original inline style back in.

And correcting wp_get_attachment_url($attachment_ids) to call only the first thumbnail

<div style='background-image: url(
   <?php   /// first inline style
echo get_the_post_thumbnail_url();
?>);' onMouseOut="this.style['background-image']='url(
   <?php /// Return to Original Position
echo get_the_post_thumbnail_url();
?>)';" onMouseOver="this.style['background-image']='url(
   <?php /// Hover Effect
global $product;
$attachment_ids = $product->get_gallery_attachment_ids();
echo $image_link = wp_get_attachment_url($attachment_ids[0]);
?>
  )';">
GibsonFX
  • 1,000
  • 2
  • 10
  • 33