I simply want to remove the <button> element but keep the text in button at a max-width: 768px media query using JavaScript. I understand it is currently jQuery. I have it working to remove the button but cannot get the media query condition to work.
Here is the button, removed with JavaScript:
$(".rent").replaceWith(function() {
return $(this).text();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="rent">Rent</button>
Here is what I tried to remove the button with a media query condition, but it does not work:
const mediaQuery = window.matchMedia('(max-width: 768px)');
if (mediaQuery.matches) {
$(".rent").replaceWith(function() {
return $(this).text();
});
}
Here is update that half way works with event listener, but breaks on resizing back.
function checkMediaQuery() {
const mediaQuery = window.matchMedia('(max-width: 768px)');
if (mediaQuery.matches) {
$(".rent").replaceWith(function() {
return $(this).text();
});
}
}
window.addEventListener('resize', checkMediaQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="rent">Rent</button>
Your replace code should work, just depends on how and when you call it.
Although assuming you still want the button to do whatever it does, you could just style the button to look like text using css @media rules.
@media only screen and (max-width: 480px) {
button.rent {
background-color: transparent;
border: none;
}
}
<button class="rent">RENT</button>