How do I make document side script conditional? - javascript

So I'm having trouble breaking my horizontal scroll when the viewport is 480px or below. My scroll has this document-side script:
<script>
$(function () {
$("#wrapper").wrapInner("<table><tr>");
$(".post").wrap("<td>");
});
$(function () {
$("body").mousewheel(function (event, delta) {
this.scrollLeft -= (delta * 50);
event.preventDefault();
});
});
</script>
When I remove the table wrapping feature then the scroll breaks. Instead I'm hoping for one of these two possible fixes:
a media query command that forces the removal of a class(es) so I can then display as a block.
a way to make the above document-side code conditional on viewport size.
Thanks in advance. I know its not the neatest, but its the only way I was able to get the scroll to work (except on IE)
Thanks in advance.

Here is one way to only horizontally scroll if body is more than 480px wide:
$("body").mousewheel(function (event, delta) {
var $this = $(this); // 'body' in this case
var widthLimit = 480;
if ($this.width() > widthLimit) {
// horizontal scroll
this.scrollLeft -= (delta * 50);
event.preventDefault();
}
});
Here is the media query that will display #wrapper as a block if the viewport is less than 480px:
#media only screen and (max-width: 480px) {
#wrapper {
display: block;
}
}
Note that media queries can generally only change styling and not add or remove classes or ids.

Related

How to run a jQuery Function in smaller width?

I want to do a something in a smaller width of screen But I have a problem. I'm creating a Responsive Navbar, So I want to show a Button when It is in small width & toggling the Menu. But when I hide the Menu in smaller width, It doesn't show the Menu in wider width Because of Hiding in jQuery ...
So I wanted to make jQuery Codes run JUST in smaller width, I wrote this But It doesn't work :
$(window).resize(function() {
if($(window).width() < '48em') {
$('.ji-toggle-btn').click(function() {
$(this).parent().find('ul').toggle();
});
}
});
The proper way to show/hide a button is with a media query in CSS:
.css example:
.ji-toggle-btn {
display: none;
}
#media (min-width: 48em) {
.ji-toggle-btn {
display: block;
}
}
.scss example:
.ji-toggle-btn {
display: none;
#media (min-width: 48em) {
display: block;
}
}
I mocked up a sample of how to do a responsive sidebar:
http://codepen.io/staypuftman/pen/dGOMYO
What you'll notice in this example is how little JS is used. Targeting a .toggle class and using css transitions will get you where you want to go. You're overthinking this approach with the JS.
Your problem is that you're assigning a behavior on smaller resolution. You practically want to assign a click event only when the window size is smaller than 48 em.
With simple words - just remove the click event:
$(window).resize(function() {
if($(window).width() < '48em') {
$('.ji-toggle-btn').parent().find('ul').toggle();
}
});
EDIT I agree with the guy above about the CSS. Those things basically should be done with media queries.
$(window).width() returns an int (screen width in pixels). In order to get that value in ems you need to divide that buy the body's font-size, then compare that with just '48' not '48em'. For example:
$(window).resize(function() {
if(($(window).width() / parseFloat($("body").css("font-size"))) < 48) {
// Do stuff here...
}
});

Position displacement when toggling several overflow-y Elements

I have a problem which I don't know how to solve, hopefully someone here can shed some light into it.
I have a very simple layout (JSBin) with a horizontally centered header, some content to experience vertical scrolling, a sticky footer and an off-canvas navigation menu. I want to prevent the user from scrolling the page when the sidebar is opened, I'm doing that by toggling a class on the <html> tag:
$('button').click(function () {
$('html').toggleClass('sidebar');
});
The .sidebar class will transition the sidebar into view and disable scrolling on the content:
html {
overflow-y: scroll; /* default state, always shows scrollbar */
}
html.sidebar {
overflow-y: hidden; /* hides scrollbar when .sidebar is on canvas */
}
html.sidebar aside {
-webkit-transform: translate3d(-100%, 0, 0); /* places .sidebar on canvas */
}
The problem is, it displaces every element in the page by whatever width the <html> scrollbar had.
Is there any way to prevent this shift in position (preferably without resorting to Javascript)?
Here's the JSBin editor in case you need to peek at the code.
Update: Seems that Javascript isn't an option, the scroll width calculation is not reliable at all.
You can toggle the margin-right of .container to compensate for the change in width
$(function () {
$('button').click(function () {
var marginR = $(".container").css("margin-right") == sWidth+"px" ? "auto" : sWidth;
$(".container").css("margin-right", marginR);
$('html').toggleClass('sidebar');
});
});
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
var sWidth = getScrollbarWidth();
Demo
Scrollbar width calculation taken from this answer
I can't find a CSS solution that works reliably. However, I'm having success with the following Javascript:
window.onload=function(){
document.body.style.paddingLeft = (window.innerWidth - document.body.clientWidth);
document.body.onclick=function(){
document.body.style.paddingLeft = (window.innerWidth - document.body.clientWidth);
}
}
I haven't analyzed yet what the processing impact is for running this code each and every time somebody clicks on my site (it's probably ugly), but it works.

Slider script show different ammount of items on resize

I have a slide script where you can set the ammount of visible images and need to change the ammount when I reach a browser size.
When browser width is smaller than 768px show 4 items.
Is this possible to combine below 2 scripts?
FIDDLE
Slider script:
$('.logo-slide').wmuSlider({
touch: Modernizr.touch,
animation: 'slide',
items: 5
});
Browser width script:
$(window).resize(function() {
if ($(window).width() < 767) {
$(".nav-wide").hide();
}
else {
$(".nav-wide").show();
}
});
I try to combine these like below script, but it doesn't work
$(window).resize(function() {
if ($(window).width() < 768) {
$('.logo-slide').wmuSlider({
items: 4
});
}
else {
$('.logo-slide').wmuSlider({
items: 5
});
}
});
Your window.width and resize methods are spot on for detecting the different screen sizes.
The jquery plugin is probably developed to be called only once on page load.
A plugin like this might be a better option where you can have minimum and maximum item numbers?
http://www.woothemes.com/flexslider/ (see // Carousel Options minItems and maxItems)
Try CSS3
#media screen and (max-width: 767px) {
.logo-slide { display: none; }
}

CSS Media Query and Javascript/jQuery don't match up

In my CSS I have a media query like so:
#media (min-width: 800px) { /* styles */ }
And then in my jQuery, I'm targeting the window width and performing some actions.
Edit: as per the answers below, I have changed this function but my JS and CSS still didn't align. The problem was fixed by using the Modernizr function as specified in the accepted answer.
$(window).resize(function() {
var viewportWidth = $(window).width();
if (viewportWidth >= 800) {
// do something
}
});
The problem is that while the jQuery is executing bang on 800px or more, the CSS is kicking in at 740px.
Is there a known problem with these not aligning? Or could there be something on my page affecting the CSS and why it's 740px not 800px? Maybe there's something else I should be using instead of $(window)?
Edit: I've tested in Safari and it works perfectly. In Chrome and Firefox, the jQuery functions run spot on to 800px and so does the CSS. But in Chrome, the CSS actually runs after 740px, even though the media query is 800px - how can I get these to align perfectly?
You can use Modernizr to execute the media query in JS (the mq() method will return a boolean):
$(window).resize(function() {
if (Modernizr.mq('(min-width: 800px)')) {
// do something
}
});
Move your width check, or else the viewportWidth variable will always be the same thing:
$(window).resize(function() {
var viewportWidth = $(this).width();
if (viewportWidth >= 800) {
// do something
}
});
Valid code would be:
$(window).resize(function() {
var viewportWidth = $(window).width();
if (viewportWidth >= 800) {
// do something
}
});
Everytime window resizes the new value will be stored in viewportWidth variable. In your code viewportWidth gets the only value of the $(window).width() when the page was loaded.
What I just tried, and it seems to work, is to use the CSS media query to style an object, and then use javascript to test if the object has that style. Javascript is asking CSS what the answer is, rather than having two parts of the page determine it separately:
CSS:
#media (min-width: 800px) {
#viewType {width:3px;}
}
HTML :
<div id="viewType" style="display:none"></div>
JavaScript:
var answer = ($("#viewType").width()==3)
I agree with Steve answer. the jquery(window).width(); is does not match with the media queries and even doesn't provide accurate window width size. here is my answer taken from Steve and modified.
CSS :
#media (max-width: 767px) {
//define your class value, anything make sure it won't affect your layout styling
.open {
min-width: 1px !important;
}
}
.open {
min-width: 2px;
}
Js :
// when re-sizing the browser it will keep looking for the min-width size, if the media query is invoked the min-width size will be change.
$(window).on('resize orientation', function() {
var media = $('.open').css('min-width');
if( media == '1px') // means < 767px
{
// do your stuff
}
});
That's it~ hope it help.

Detecting a screen's width with Javascript

if(screen.availWidth > 850){
//Do this
} else {
//Do this
}
This is what I have right now. My issue right now is if someone was to zoom in to the page, I want the width to change as it will affect how the page is displayed.
Shouldn't you be more worried about someone resizing their browser window? Not everyone keeps their browsers maximized.
To do this:
if( (window.innerWidth || document.documentElement.clientWidth) > 850) {
// do something
}
else {
// do other thing
}
I'm fairly sure this takes the zoom into account, but I've never tested that.
Bind an event handler to the window.onresize event:
window.onresize = function(event) {
if (screen.availWidth > 850) { ... }
};
If you use jQuery:
$(window).resize(function(){
if ($(window).width() > 850) { ... }
});
Besides, if you want to create a responsive design, consider using CSS media queries. This automatically adapts the page if the user zooms or resizes the browser window and also works if the user has JavaScript deactivated.
/* CSS */
#media (min-width: 850px) {
/* style */
}

Categories