I have an issue loading jQuery on the WooCommerce single product page.
I need to make a dynamic onclick change with jQuery: adding: 'border: xx xx xx'
to the .woocommerce-product-gallery__wrapper
css class.
My code:
Hook (placed in WooCommerce functions.php):
add_action( 'woocommerce_after_single_product_summary', 'jquery_script_after_single_product_summary' );
function jquery_script_after_single_product_summary() {
?>
<script type="text/javascript">
//**START CHANGE FRAME PRODUCT PAGE**//
jQuery(document).ready(function() {
$("select.frame").change(function() {
var changeframe = $(this).children("option:selected").val();
$('.woocommerce-product-gallery__wrapper').css('border', changeframe);
});
});
//END CHANGE FRAME PRODUCT PAGE**//
</script>
<?php
}
Html selector to make onclick change (placed on the single product page):
<select class="frame">
<option value="">Choose frame</option>
<option value="">Without frame</option>
<option value="20px solid black">Red</option>
<option value="20px solid blue">Blue</option>
<option value="20px solid purple">Yellow</option>
</select>
<br><br><br>
<figure class="woocommerce-product-gallery__wrapper"><img src="image.jpg"></div>
What could be the issue? It works on online simulations but not in WordPress (WooCommerce). Am I placing the script in the wrong place or perhaps not loading a correct jQuery script file...?
I'm not using any Cache.
Any advice?
If you view the console tab in your browser with your existing code, you will see the following error message
jQuery.Deferred exception: $ is not a function TypeError: $ is not a function
The code below will solve that problem. The display of the HTML (drop-down list) can be applied anywhere on the page via template overrides or via the desired hook.
In this answer I have combined both in one
function action_woocommerce_after_single_product_summary() {
// Display drop-down list
echo '<select class="frame">
<option value="">Choose frame</option>
<option value="">Without frame</option>
<option value="20px solid red">Red</option>
<option value="20px solid blue">Blue</option>
<option value="20px solid yellow">Yellow</option>
</select>';
?>
<script>
jQuery(document).ready(function($) {
// On change
$( 'select.frame' ).change( function() {
var changeframe = $(this).children( 'option:selected' ).val();
// DEBUG
console.log(changeframe);
// Add border
$( '.woocommerce-product-gallery__wrapper' ).css( 'border', changeframe );
});
});
</script>
<?php
}
add_action( 'woocommerce_after_single_product_summary', 'action_woocommerce_after_single_product_summary', 10, 0 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.