I'm trying to replace gray box PNG with red box SVG, whose width should vary depending on the screen width.
This is the working code using .replaceWith()
before implementing window.matchMedia()
$(document).ready(function(){
$('.site-branding').replaceWith('<embed src="https://static1.squarespace.com/static/51b172e5e4b021e974bb4989/t/63f595b6fffc00778090a066/1677039030495/red.svg" width="200">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="site-branding" data-content-field="site-title">
<h1 class="image">
<a href="https://google.com">
<img src="https://i.imgur.com/GgFugEL.png">
</a>
</h1>
</div>
And this is the broken code using .replaceWith()
after implementing window.matchMedia()
$(document).ready(function() {
function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
$('.site-branding').replaceWith('<embed src="https://static1.squarespace.com/static/51b172e5e4b021e974bb4989/t/63f595b6fffc00778090a066/1677039030495/red.svg" width="50">');
} else {
$('.site-branding').replaceWith('<embed src="https://static1.squarespace.com/static/51b172e5e4b021e974bb4989/t/63f595b6fffc00778090a066/1677039030495/red.svg" width="200">');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="site-branding" data-content-field="site-title">
<h1 class="image">
<a href="https://google.com">
<img src="https://i.imgur.com/GgFugEL.png">
</a>
</h1>
</div>
I don't understand why my second code is broken. I double-checked the syntax. Both window.matchMedia()
and .replaceWith()
fail to execute.