console.log and alert returning different values. Code is regarding to find Computed Style of left
property.
$(document).ready(function() {
const smallDevice = window.matchMedia("(max-width: 1490px)");
smallDevice.addListener(handleDeviceChange);
function handleDeviceChange(e) {
if (e.matches) {
const left = $(".sidebar").css("left");
alert(left);
console.log(left);
}
}
});
@media (max-width: 1490px) {
.sidebar2 {
right: -300px !important;
}
.sidebar {
left: -300px !important;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<aside class="sidebar" id="sidebar">
<ul class="sidebar-nav" id="sidebar-nav">
<li class="nav-item">
<a class="nav-link">
<img class="logo" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR3pZ-gZavZ--zmy5TluKQHw-5aKDXYlrnnbQ&usqp=CAU" />
</a>
</li>
<li class="nav-item">
<a class="nav-link">
<i class="bi- bi-calendar-event "></i>
<span>الأحداث</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link">
<i class="bi- bi-newspaper "></i>
<span>الأخبار</span>
</a>
</li>
</ul>
</aside>
<aside class="sidebar2" id="sidebar2">
<ul class="sidebar-nav" id="sidebar-nav">
<li class="nav-item">
<a class="nav-link">
<img class="logo" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR3pZ-gZavZ--zmy5TluKQHw-5aKDXYlrnnbQ&usqp=CAU" />
</a>
</li>
<li class="nav-item">
<a class="nav-link">
<i class="bi- bi-calendar-event "></i>
<span>الأحداث</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link">
<i class="bi- bi-newspaper "></i>
<span>الأخبار</span>
</a>
</li>
</ul>
</aside>
2
Answers
I think your code is mostly correct, but you are using id selector instead of class selector.
Also, you need to use
e.matches
instead ofsmallDevice.matches
.This code works fine:
With addEventListener, It returns the same values in alert and console.log