I am trying to show or hide a div called "contact-form" on website based on another divs a css class, which is connected to whether a product is in or out of stock.
It needs to show the div if the class is "in-stock", and hide if it's class is "out-of-stock"
any ideas? struggling to figure it out!
<div id="contact-form"></div>
<p class="stock in-stock"></p> <!-- if product is in stock this shows-->
<p class="stock out-of-stock"></p> <!-- if out of stock this show-->
<script>
if ('p.in-stock') {
('#contact-form').show();
}
else {
('#contact-form').hide();
}
</script>
Website is here - http://trent-art.co.uk/shop/barnes-david-still-life-of-flowers/ - out of stock product which needs the "submit best offer" button hiding if out of stock.
$('#contact-form').toggle($('p.stock').hasClass('in-stock'));
OR
if ($('p.stock').hasClass('in-stock')) {
$('#contact-form').show();
} else {
$('#contact-form').hide();
}
Since you didn't tag your question with jQuery
, here is a vanilla JS alternative:
var formDiv = document.getElementById("contact-form");
var stockPara = document.getElementsByClassName("stock");
var sStockClass = stockPara[0].className;
formDiv.style.display = (sStockClass.indexOf("in-stock") < 0) ? "none" : "block";
This code could be shortened into fewer lines (technically, you could do it in one), but I left it broken up for clarity. The "consolidated" version would be:
document.getElementById("contact-form").style.display =
(document.getElementsByClassName("stock")[0].className.indexOf("in-stock") < 0) ?
"none" : "block";
If you're not familiar with ternary operators, that is what I used in the last line . . . it's basically a one-condition, two-option, one-line, if
statement. The code says, "if 'in-stock' is in the sStockName
string value, then assign 'block' as the display
value, otherwise, use 'none'"
More info on ternaries here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
if there is 1 contact form per product then put div of contact form inside product and hide with css :
.in-stock + .showOrHide
{
display:block;
}
.sold + .showOrHide
{
display:none;
}
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.