Jquery: How to check if input is focused - javascript

I am building a mobile web app where the page is set to responsive through screen width and height. I am facing one issue here. In a mobile, if I click any input field, the screen size changes due to mobile keypad in some browsers. In this case I don't want the screen to resize. Where as the screen has to resize when we rotate screen. Your help will be greatly appreciated. Below is the part of code I am using for that.
function pageresponsive() {
$('body').css('width', window.screen.width);
$('body').css('height', window.screen.height);
}
pageresponsive();
var input_click_status = 0;
$("input").click(function() {
input_click_status = 1;
});
$( "input" ).focus(function() {
input_click_status = 1;
});
//This might not work as resize event will be set at the time of page load
if(input_click_status == 0) {
$(window).resize(function() {
pageresponsive(true);
});
}

Try this solution
var isFocused = $("input").is(":focus")

for version 1.6+ of jquery
$("selector").is(":focus")
:Focus

you can check by two way:
you can bind an event on input.
var is_focused = false;
jQuery('input').bind('focus', function(){
is_focused = true;
/* you can write code what ever you want to do on focus.*/
});
or
there is one more function:
var is_focused = jQuery("input").is(":focus")

Related

Execute javascript only above certain width with resize

I'm currently developing a website which has a sticky menu function. I've got the normal javascript to work good, which adds some classes once the client scrolls past 150px.
I now face the problem that I don't want the classes to be added once people view the website below 725px, so I added a rule that it only executes the script above 725px but the problem is this:
If I resize the window back to full the function won't work anymore, so I created another rule with the javascript resize function but I can't get it to work..
Here is my script:
$(document).ready(function(){
var mainbottom = 150;
if($(window).innerWidth() > 725) {
$(window).on('scroll',function(){
stop = Math.round($(window).scrollTop());
if (stop > mainbottom) {
$('.header').addClass('sticky-nav');
$('.logo').addClass('sticky-logo');
$('.navigation').addClass('sticky-menu');
} else {
$('.header').removeClass('sticky-nav');
$('.logo').removeClass('sticky-logo');
$('.navigation').removeClass('sticky-menu');
}
});
}
});
$(window).resize(function() {
var mainbottom = 150;
if($(window).innerWidth() > 725) {
$(window).on('scroll',function(){
stop = Math.round($(window).scrollTop());
if (stop > mainbottom) {
$('.header').addClass('sticky-nav');
$('.logo').addClass('sticky-logo');
$('.navigation').addClass('sticky-menu');
} else {
$('.header').removeClass('sticky-nav');
$('.logo').removeClass('sticky-logo');
$('.navigation').removeClass('sticky-menu');
}
});
}
});
I'll hope somebody can help me with this problem.
First off, you should keep your code DRY. So preferably never copy paste any code around, bacause you will have to edit all the copies when you have to alter the behaviour or fix bugs.
You have not but your second $(window).resize() handler in the onready handler, so maybe that is why it is not triggered.
This should work:
$(document).ready(function(){
var mainbottom = 150;
function onScroll () {
stop = Math.round($(window).scrollTop());
if (stop > mainbottom) {
$('.header').addClass('sticky-nav');
$('.logo').addClass('sticky-logo');
$('.navigation').addClass('sticky-menu');
} else {
$('.header').removeClass('sticky-nav');
$('.logo').removeClass('sticky-logo');
$('.navigation').removeClass('sticky-menu');
}
}
var widthExceeded = false;
$(window).resize(function() {
$(window).innerWidth() > 725) {
if (!widthExceeded) {
$(window).on('scroll', onScroll);
}
widthExceeded = true;
} else {
if (widthExceeded) {
$(window).off('scroll', onScroll);
}
widthExceeded = false;
}
}).resize();
});
You are defining a scroll event listener inside a resize event listener, so basically you're declaring the scroll listener on every resive event (so the scroll listener is defined many many times if the user resize its browser). You need to correct this.
You could declare a flag (boolean) to indicate wether the viewport is below 725px or not. It should be initialized on $(document).ready(...) by testing the viewport dimensions.
Create a resize event listener which updates this flag by testing the viewport width, so you always know if you need to manage your classes or not.
At this point, console.log(your_flag) in your resize event listener to check if it works fine.
Then declare a scroll event listener, and in this listener the first thing you want to do is test the flag value. If viewport > 725, then manage the classes, otherwise do nothing.

Dynamically add class on browser resize (viewport width)

I have an element called jobfilter, which I want to add a class to depending on the viewport width, ie. when I resize my browser to <1000px, I want to add the class .hidden to .jobfilter.
Now, I managed to get it half-working with the help of this link: $(window).width() not the same as media query.
Using this:
function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
//...
} else {
//...
}
}
Here's my JSFiddle: http://jsfiddle.net/ck55Lf01/10/.
If you resize the browser and refresh the page, the jobfilter hides, but I'd like that to happen dynamically, not on the refresh of the page, thank you for your help!
This is a fucnction I use to dynamically check the window width on resize, I wrapped it in a document ready function that passes the $ as a parameter to prevent any conflicts that might occur with other javascript libraries that use the $. An example would be if you were to use your function inside of a wordpress theme or plugin.
Jsfiddle example: http://jsfiddle.net/larryjoelane/ck55Lf01/24/
Javascript:
/*
document ready function used to prevent conflict with other javascript libraries
that use the $ parameter
*/
jQuery(document).ready(function($){
//get the window width
var winWidth = $(window).width();
//set the maxWidth
var maxWidth = 1000;
//if the window width is less than the maxWidth pixels on document loading
if(winWidth < maxWidth){//begin if then
//add the class hidden to .jobFilter
$(".jobfilter").addClass("hidden");
}//end if then
$(window).resize(function(){//begin resize event
//get the window width
var winWidth = $(window).width();
//set the maxWidth
var maxWidth = 1000;
//if the window width is less than maxWidth pixels
if(winWidth < maxWidth){//begin if then
//add the class hidden to .jobFilter
$(".jobfilter").addClass("hidden");
}
else{
//remove the class hidden
$(".jobfilter").removeClass("hidden");
}//end if then else
});//end window resize event
});//end document ready function
Update August 2021
It's still a little-known fact that matchMedia has an event listener. It triggers a "change" event whenever it changes. You can use that to toggle a class depending on whether or not it matches, and listen for that match changing without having to bind anything to the (potentially heavy) window resize event.
function doSomething(matches) {
if (matches) {
// media query matches
} else {
// media query does not match
}
}
const query = window.matchMedia("(max-width: 767px)");
query.addEventListener("change", ({ matches }) => doSomething(matches));
doSomething(query.matches);
This is also mentioned on MDN.
Original Answer
Little known fact: matchMedia has an event listener:
function handleMedia(mql) {
if (mql.matches) {
// media query matches
} else {
// media query does not match
}
}
var mql = window.matchMedia('(max-width: 767px)').addListener(handleMedia);
handleMedia(mql);
The event listener will execute every time the browser matches or unmatches the media query. In your case, I'd recommend firing the handler manually as well (as shown in the example) to be sure to get the correct class set on load.
This example is taken from MDN (although it's pretty well hidden).
you have to listen on the resize event.
$( window ).resize(function() {
checkPosition();
});
Use the resize event to check if the window is resized or not. Use this code
$( window ).resize(function() {
function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
//...
} else {
//...
}
}
}
Hope this helps you
$(document).ready(function(){
DOaction(); // run function after document ready
$(window).on('resize',DOaction); // on resize window run function
});
// function to add and remove hidden class
function DOaction(){
if($(window).width() <= 1000){
$(".jobfilter").addClass('hidden');
}else{
$(".jobfilter").removeClass('hidden');
}
}
Jsfiddle

Add onhover to my page when I display it on smartphone

When I use your page from your computer when you hover the mouse over the menu, I received a menu to select the language.
The same thing I want to do when using the hand on the smartphone.
I am Trying to use this Hammer.js, but it does not work. Below my code.
$(document).ready(function(){
var languageToChange = $('.lang-list a');
var change = Hammer(languageToChange).on('tap', function(event){
alert(event);
});
});
You should detect width of the screen and if it is under 780px than use tap, otherwise use hover event. Bootstrap can help you a lot making resposive site. If you don't want to use it try something like this:
function desktopEvent( text ){
alert( "Desktop:" + text );
}
function mobileEvent( event ){
alert( "Mobile" + text );
}
$(document).ready(function(){
var languageToChange = $('.lang-list a');
var change;
if ( $(document).width() < 780){
change = Hammer(languageToChange).on('tap', mobileEvent( event ));
} else {
change = Hammer(languageToChange).on('mouseover', desktopEvent( event ));
}
});

jQuery Dual Range Slider Reload

I want to build an dual range slider in jQuery by my own.
My first attempt kind of works. But sometimes if I release the mouse button after dragging a slide the website automatically reloads.
I've uploaded my Code on jsfiddle:
http://jsfiddle.net/u2d8P
Here is the js part:
$(document).ready(function () {
var $dragging = null;
$('.slider').bind("mousemove", function(e) {
if ($dragging) {
if (e.pageX<200) {
$dragging.offset({
left: e.pageX
});
}
}
});
$('.left_slider').bind("mousedown", function (e) {
$dragging = $(e.target);
});
$('.right_slider').bind("mousedown", function (e) {
$dragging = $(e.target);
});
$('.slider').bind("mouseup", function (e) {
$dragging = null;
});
});
Even in the fiddle it reloads sometimes after releasing the mouse button.
What am I doing wrong?
Thanks in advance for your help!
Greetz
Since your anchors (do they even need to be anchors?) have no href value (which is invalid, btw), the default action is to reload the current page. You'd need to either use preventDefault to stop that, or use a value such as # or javascript:void(0).
http://jsfiddle.net/isherwood/u2d8P/1/
Here's how you'd do it using preventDefault. Credit to Joe Cullinan.
http://jsfiddle.net/hPkS6

How do I disable vertical scrolling in iOS using Hammer.js?

I'm trying to disable vertical scrolling in iOS with Hammer.js (jQuery version) in a horizontally scrolling list. I've tried this:
$(document).hammer().on('swipe,drag', 'body',
function(event)
{
if (event.direction == Hammer.DIRECTION_UP || event.direction == Hammer.DIRECTION_DOWN)
{
event.preventDefault();
}
}
);
But it doesn't work. So, how do I disable the scroll vertically while still being able to scroll horizontally?
I did it using the event.gesture.preventDefault:
$('#horizontalCarousel').hammer({ drag_lock_to_axis: true }).on("swipe drag", function(event) {
event.gesture.preventDefault();
if(event.type == "swipe"){
swipeAction(event);
} else {
dragAction(event);
}
});
Here is the given documentation
[EDIT]
My answer was only to let you know you were using the wrong event.preventDefault(). In fact you also used the wrong syntax to check the event direction. You should be able to manage it in this way, though I haven't tested it:
$(document).hammer({ drag_lock_to_axis: true }).on("swipe drag", function(event) {
if (event.gesture.direction == Hammer.DIRECTION_UP || event.gesture.direction == Hammer.DIRECTION_DOWN){
event.gesture.preventDefault();
}
});
2 things are changed: event.gesture.direction and event.gesture.preventDefault(); The event.direction was the way to do it on older versions of hammer js.
Note: if you want to do something with the swipe event, for instance: jump a bigger amount horizontally when swiping, you can combine my answers.
You can use the drag_block_vertical option to disable vertical scrolling:
$(document).hammer({drag_block_vertical: true}).on('swipe,drag', 'body', function(event){
// etc
});
Also, you're calling it on the body element, which should always exist. For that reason, you could probably simplify to:
$('body').hammer({drag_block_vertical: true}).on('swipe,drag', function(event){
// etc
});
Check out this page:
https://github.com/EightMedia/hammer.js/wiki/Event-delegation-and-how-to-stopPropagation---preventDefaults#evgesturestoppropagation
Try this assuming your $ is jQuery and you are using the jQuery version of hammer.js
$('body').hammer().on('touch', function(ev){
var $t = $(ev.target); //let's you know the exact element you touched.
if(ev.gesture.direction === 'left' || ev.gesture.direction ==='right'){
} else {
ev.gesture.preventDefault();
}
});
Hammer(document.body, { prevent_defaults: true });

Categories

Resources