How to combine this scripts correctly? - javascript

I have 2 scripts which can't work parallel. The first one is for scrolling to the search bar when it's focused, the other one removes focus when youre scrolling (to remove keyboard on mobile).
Is there a way to combine these scripts, to have it scrolling first to the search bar and then have the second script get activated if you scroll again for removing the keyboard? Because right now it's scrolling to the search bar and then it loses focus.
To scroll it to the search bar:
$("#myInput").click(function () {
$("html, body").animate({ scrollTop: $("#osb").offset().top }, 300);
return true;
});
To remove focus when scrolling again:
document.addEventListener("scroll", function() {
document.activeElement.blur();
});
Thanks already!
Example:
$("#myInput").click(function() {
document.removeEventListener("scroll", blurElement);
$("html, body").animate({
scrollTop: $("#b").offset().top
}, 300, function() {
document.addEventListener("scroll", blurElement);
});
return true;
});
function blurElement() {
document.activeElement.blur();
}
document.addEventListener("scroll", blurElement);
#a {
height: 100px;
background: #aaa;
}
#b {
background: #bbb;
}
#c {
height: 1000px;
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">
</div>
<div id="b">
<input type="text" id="myInput" placeholder="search.." title="">
</div>
<div id="c">
^ need this stay focused untill I scroll again
</div>

Maybe using a flag to prevent "blurring" while your animation is running;
var allowBlur = true;
$("#myInput").click(function () {
allowBlur = false;
$("html, body").animate({ scrollTop: $("#osb").offset().top }, 300, function() {
allowBlur = true;
});
return true;
});
document.addEventListener("scroll", function() {
if(!allowBlur) return;
document.activeElement.blur();
});
Attempt #2
$("#myInput").click(function () {
document.removeEventListener("scroll", blurElement);
$("html, body").animate({ scrollTop: $("#osb").offset().top }, 300, function() {
document.addEventListener("scroll", blurElement);
});
return true;
});
function blurElement() {
document.activeElement.blur();
}
document.addEventListener("scroll", blurElement);
Attempt #3
It appears that for some reason the "scroll" event is still being sent even when the animation is done. So based on this answer https://stackoverflow.com/a/8791175/1819684 I used a promise but I still needed a setTimeout to give the "scroll" time to end.
$("#myInput").click(function() {
document.removeEventListener("scroll", blurElement);
$("html, body").animate({
scrollTop: $("#b").offset().top
}, 300).promise().done(function() {
setTimeout(function() {
document.addEventListener("scroll", blurElement)
}, 100);
});
return true;
});
function blurElement() {
document.activeElement.blur();
}
document.addEventListener("scroll", blurElement);
#a {
height: 100px;
background: #aaa;
}
#b {
background: #bbb;
}
#c {
height: 1000px;
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">
</div>
<div id="b">
<input type="text" id="myInput" placeholder="search.." title="">
</div>
<div id="c">
</div>

Related

keep moving an element up and down while mouse button is pressed

Everything works here but I need to keep moving act up and down while mouse button is pressed, without repeated clicks.
Any help?
$('button').on('click', function(){
let a = $('.act');
a.insertBefore(a.prev());
});
$('button').on('contextmenu', function(e){
e.preventDefault();
let a = $('.act');
a.insertAfter(a.next());
});
.act{background:gold;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class='title act'>LOREM</div>
<div class='title'>IPSUM</div>
<div class='title'>DOLOR</div>
<div class='title'>SIT</div>
<div class='title'>AMET</div>
</div>
<br>
<button>CLICK</button>
Instead of the click and contextmenu events you'll have to use mouse events, here is an example:
let intervalId;
const a = $('.act');
$('button').on('mousedown', function(event) {
function fn () {
if (event.button == 0) {
a.insertBefore(a.prev());
} else if (event.button == 2) {
a.insertAfter(a.next());
}
return fn;
};
intervalId = setInterval(fn(), 500);
});
$(document).on('mouseup', function(event) {
clearInterval(intervalId);
});
$('button').on('contextmenu', function(event) {
event.preventDefault();
});
.act {
background: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class='title act'>LOREM</div>
<div class='title'>IPSUM</div>
<div class='title'>DOLOR</div>
<div class='title'>SIT</div>
<div class='title'>AMET</div>
</div>
<br>
<button>CLICK</button>
In this example, I'm using an interval to move the element every 500 milliseconds while the mouse pointer is down, I'm also preventing the contextmenu event so that the context menu will not consume the mouseup event itself.
I've made a fiddle to illustrate:
https://jsfiddle.net/10cgxohk/
html:
<p class="">x</p>
css:
.move {
animation: MoveUpDown 1s linear infinite;
position: relative;
left: 0;
bottom: 0;
}
#keyframes MoveUpDown {
0%, 100% {
bottom: 0;
}
50% {
bottom: 15px;
}
}
javascript:
$('body').on('mousedown', function() {
$('p').addClass('move');
$('body').on('mouseup', function() {
$('p').removeClass('move');
$('body').off('mouseup');
console.log('here');
})
});
This is really rough and creates an issue if you have other 'mouseup' callbacks on the body, but if that's not a worry for you then it should work. The javascript is adding a class to the element, and the class is animated in css

Scroll to id function jQuery

So I have been making onepage websites for a while now, and one thing witch is always annoys me is navigation functions witch i'm repeating for the amount of buttons and id's I have.
It looks like the following:
$('#homeB').click(function () {
$('html, body').animate({
scrollTop: $("#home").offset().top
}, 1000);
return false;
});
$("#aboutB").click(function() {
$('html, body').animate({
scrollTop: $("#about").offset().top
}, 1000);
return false;
});
$("#winesB").click(function() {
$('html, body').animate({
scrollTop: $("#wines").offset().top
}, 1000);
return false;
});
Question is, how do I change from here to a small function that does not need repeating.
Thanks.
Note: Preferably no 3rd party plugins etc. keep it in JavaScript/jQuery.
To avoid writing duplicate code, you could do a little something like this:
$(function() {
$('li').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($(e.target).attr("href")).offset().top
}, 1000);
});
});
nav {
position: fixed;
top: 0;
left: 0;
}
div {
margin: 100px 0 0 0;
width: 100%;
height: 500px;
}
div:nth-child(even) {
background: #ccc;
}
div:nth-child(odd) {
background: #4c4c4c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</nav>
<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='4'></div>
function scrollTo($element) {
$('html, body').animate({
scrollTop: $element.offset().top
}, 1000);
return false;
}
then you can use it as
$('#homeB').click(function () {
scrollTo($("#home"));
});
$("#aboutB").click(function() {
scrollTo($("#about"));
});
$("#winesB").click(function() {
scrollTo($("#wines"));
});
There are a couple ways of tackling this. If I were to be doing it, I would make whatever is being clicked a class and then setting a data attribute to the destination id, like this
<span class='nav_link' data-dest='home2'>Click me to go to home 2</span>
Then you could do something like this
$('.nav_link').click(function() {
var dest = $(this).attr('data-dest');
$('html, body').animate({
scrollTop: $('#'+dest).offset().top
}, 1000);
})

Slide divs left and right transition

I have a slide left/right and right/left transition between two divs that occurs simultaneously.
Fiddle : https://jsfiddle.net/n8jyzys2/
However the current transition looks somewhat like this
(The divs are at different rows during the transition):
Slide Transition 1
The transition I would like to achieve is similar to this (Have both divs at the same row simultaneously during transition) :
Slide Transition 2
Any ideas?
JS Credit
jQuery.fn.extend({
slideRightShow: function() {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, 1000);
});
},
slideLeftHide: function() {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, 1000);
});
},
slideRightHide: function() {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, 1000);
});
},
slideLeftShow: function() {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, 1000);
});
}
});
$("#slide_two_show").click(function () {
$("#slide_one_div").slideLeftHide();
$("#slide_two_div").slideRightShow();
});
$("#slide_one_show").click(function () {
$("#slide_one_div").slideLeftShow();
$("#slide_two_div").slideRightHide();
});
HTML Code
<div>
<div id="slide_one_div">
<br>
<div class="mydiv">
<h1>Slide 1 (Left Slide)</h1>
<p>...</p>
<button id="slide_two_show">Show Slide 2</button>
</div>
</div>
<div id="slide_two_div" style = "display:none">
<br>
<div class="mydiv">
<h1>Slide 2 (Right Slide)</h1>
<p>...</p>
<button id="slide_one_show">Show Slide 1</button>
</div>
</div>
</div>
Style
.mydiv {
background: green;
width: 100%;
height: 100px;
outline: 1px solid #f93;
}
Add this CSS to your page:
#slide_one_div {
position: absolute;
width: 100%;
}
Hope I helped ;)

How to show a indicator when clicked on a Button in this case

On Click Of the Try Again Button , is it possible to show some processing happening on the device
My jsfiddle
My code as below
$(document).on("click", ".getStarted", function(event) {
// Simulating Net Connection here
var a = 10;
if (a == 10) {
$('#mainlabel').delay(100).fadeIn(300);
$('#nonetconnmain').popup({
history : false
}).popup('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
});
$(document).on('click', '.nonetconnmainclose', function(event) {
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
$(document).on("popupbeforeposition", "#nonetconnmain", function(event, ui) {
$('#mainlabel').hide();
});
With my code , the functionality is working , but it seems that the application is not doing any action
So my question is it possible to show any indication (For example , delay , progressbar , anything )
Here ya go
$(document).on("click", ".getStarted", function(event) {
$.mobile.loading("show", {
text: "",
textVisible: true,
theme: "z",
html: ""
});
// Simulating Net Connection here
var a = 10;
if (a == 10) {
setTimeout(function() {
$.mobile.loading("hide");
$('#mainlabel').fadeIn(300);
}, 1000);
$('#nonetconnmain').popup({
history: false
}).popup('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
});
$(document).on('click', '.nonetconnmainclose', function(event) {
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
$(document).on("popupbeforeposition", "#nonetconnmain", function(event, ui) {
$('#mainlabel').hide();
});
.popup {
height: 200px;
width: 150px;
}
.popup h6 {
font-size: 1.5em !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<link href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" rel="stylesheet" />
<div data-role="page">
<div data-role="popup" id="nonetconnmain" data-dismissible="false" class="ui-content" data-theme="a">
<div class="popup_inner popup_sm">
<div class="popup_content" style="text-align:center;">
<p class="">Please check net connectivcty</p>
<label id="mainlabel" style="margin:100px auto 60px auto;color:Red; line-height:40px;font-size:medium;display:none">Please check</label>
</div>
<div class="popup_footer nonetconnmainclose">
<a class="">Try Again</a>
</div>
</div>
</div>
<button class="getStarted btn btn-a get_btn">Click Here</button>
</div>
You can use a small function (with time as parameter) and use jQuery animate() to create the process effect like below.
var updateProgress = function(t) {
$( "#p" ).css("width",0);
$( "#p" ).show();
$( "#p" ).animate({ "width": "100%" }, t , "linear", function() {
$(this).hide();
});
}
Do notice that the time that is chosen when calling updateProgress() is relevant with the delay and the fade in effect of the text message
updateProgress(3500);
$('#mainlabel').delay(3400).fadeIn(600);
Check it on the snippet below
var updateProgress = function(t) {
$( "#p" ).css("width",0);
$( "#p" ).show();
$( "#p" ).animate({ "width": "100%" }, t , "linear", function() {
$(this).hide();
});
}
$(document).on("click", ".getStarted", function(event) {
var a = 10;
if(a==10)
{
updateProgress(3500);
$('#mainlabel').delay(3400).fadeIn(600);
$('#nonetconnmain').popup({history: false}).popup('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
});
$(document).on('click', '.nonetconnmainclose', function(event) {
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
$(document).on("popupbeforeposition", "#nonetconnmain",function( event, ui ) {
$('#mainlabel').hide();
});
.popup {
height: 200px;
width: 400px;
}
.popup h6 {
font-size: 1.5em !important;
}
#p {
border:none;
height:1em;
background: #0063a6;
width:0%;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<link href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" rel="stylesheet"/>
<div data-role="page">
<div data-role="popup" id="nonetconnmain" data-dismissible="false" class="ui-content" data-theme="a">
<div class="popup_inner popup_sm">
<div class="popup_content" style="text-align:center;">
<p class="">Please check net connectivcty</p>
<div id="p"></div><br>
<label id="mainlabel" style="margin:100px auto 60px auto;color:Red; line-height:40px;font-size:medium;display:none">Please check </label>
</div>
<div class="popup_footer nonetconnmainclose">
<a class="">Try Again</a>
</div>
</div>
</div>
<button class="getStarted btn btn-a get_btn">Click Here</button>
</div>
Fiddle
Probably when you click on try again , you can have a setinterval triggered which can check for online connectivity and when found can close the popup and get started again, also when we do retries in the interval the progress can be shown as progressing dots..
Below is the code, i haven't tried to run the code, but it shows the idea
$(document).on('click', '.nonetconnmainclose', function(event) {
var msgUI = $("#mainlabel");
msgUI.data("previoustext",msgUI.html()).html("retrying...");
var progress = [];
var counter = 0 ,timeout = 5;
var clearIt = setInterval(function(){
var online = navigator.onLine;
progress.push(".");
if(counter > timeout && !online){
msgUI.html(msgUI.data("previoustext"));
counter=0;
}
if(online){
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
counter=0;
clearInterval(clearIt);
}
else{
msgUI.html("retrying" + progress.join(""));
counter++;
}
},1000);
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
Sure,
try appending a loader GIF to one of the div and remember to remove the same when your process is finished.
Kindly refer to StackOverflow
And try appending this
$('#nonetconnmain').append('<center><img style="height: 50px; position:relative; top:100px;" src="cdnjs.cloudflare.com/ajax/libs/semantic-ui/0.16.1/images/…; alt="loading..."></center>');
This will append a loader to your HTML to show some kind of processing.

Scroll to next section

My code looks like this:
<div id="arrow">
<a class="next"></a>
<a class="previous"></a>
</div>
<section id="first">
...
</section>
<section id="second">
...
</section>
<section id="third">
...
</section>
The element #arrow has position: fixed, and I'm trying to make the window scroll to the next section when a.next is clicked.
Ex: The first time a.next is clicked, the window scrolls to section#first, the second time, the window scrolls to section#second, etc. The same thing happens to a.previous.
Does someone know how to solve this problem?
Thanks a lot!
EDIT
My JS code:
$('#arrows a.previous').click(function() {
$.scrollTo($(this).closest('section').prev(),800);
});
$('#arrows a.next').click(function() {
$.scrollTo($(this).closest('section').next(),800);
});
You will need to handle to 3 events in this case:
Current page position - updated each time.
User scrolls manualy the page.
User clicks the prev or next button.
2, 3 need to use the current page position and update him according to the direction that the page is scrolling.
My quick demos : Vertical Version jsFiddle --- Horizontal Version jsFiddle
Vertical Version snippet :
$(function(){
var pagePositon = 0,
sectionsSeclector = 'section',
$scrollItems = $(sectionsSeclector),
offsetTolorence = 30,
pageMaxPosition = $scrollItems.length - 1;
//Map the sections:
$scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); });
// Bind to scroll
$(window).bind('scroll',upPos);
//Move on click:
$('#arrow a').click(function(e){
if ($(this).hasClass('next') && pagePositon+1 <= pageMaxPosition) {
pagePositon++;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
}
if ($(this).hasClass('previous') && pagePositon-1 >= 0) {
pagePositon--;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
return false;
}
});
//Update position func:
function upPos(){
var fromTop = $(this).scrollTop();
var $cur = null;
$scrollItems.each(function(index,ele){
if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele);
});
if ($cur != null && pagePositon != $cur.data('pos')) {
pagePositon = $cur.data('pos');
}
}
});
section { min-height:800px; }
#arrow {
position:fixed;
right:0;
top:0;
background-color:black;
color:white;
}
#arrow a{
display:inline-block;
padding:10px 20px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="arrow">
<a class="next">next</a>
<a class="previous">prev</a>
</div>
<section style="background-color:green">...</section>
<section style="background-color:blue">...</section>
<section style="background-color:red">...</section>
All you need, to allow the user to use both arrows and scrollbar:
var $sec = $("section");
$(".prev, .next").click(function(){
var y = $sec.filter(function(i, el) {
return el.getBoundingClientRect().bottom > 0;
})[$(this).hasClass("next")?"next":"prev"]("section").offset().top;
$("html, body").stop().animate({scrollTop: y});
});
*{margin:0;padding:0;}
#arrow{
position:fixed;
width:100%;
text-align:center;
}
#arrow a{
display:inline-block;
background: tomato;
padding:6px 15px;
border-radius:3px;
cursor:pointer;
}
section{
height:1200px;
border:3px solid #444;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="arrow"><a class="prev">↑</a><a class="next">↓</a></div>
<section>1</section>
<section style="height:500px;">2</section>
<section>3</section>
<section style="height:600px;">4</section>
<section>5</section>
To explain the jQuery a bit:
// Cache your selectors
var $sec = $("section");
// On any of both arrows click
$(".prev, .next").click(function(){
// We need to get current element
// before defining the `.next()` or `.prev()` element to target
// and get it's `offset().top` into an `y` variable we'll animate to.
// A current element is always the one which bottom position
// (relative to the browser top) is higher than 0.
var y = $sec.filter(function(i, el) {
return el.getBoundingClientRect().bottom > 0;
})[$(this).hasClass("next")?"next":"prev"]("section").offset().top;
// (Line above:) if the clicked button className was `"next"`,
// target the the `.next("section")`, else target the `.prev("section")`
// and retrieve it's `.offset().top`
$("html, body").stop().animate({scrollTop: y});
});
i have tried to do with .closest("section") but it only works when the section is a parent of the element you clicked so this is the best way i got
sections=$("section");
s=0;
$(".next").click(function() {
if(s<sections.length-1){
s++;
$('html, body').animate({
scrollTop: sections.eq(s).offset().top
}, 500);
}});
$(".previous").click(function() {
if(s>0){
s--;
$('html, body').animate({
scrollTop: sections.eq(s).offset().top
}, 500);
}});
section{
background-color:#bbb;
width:100%;
height:700px;
border-bottom:2px solid #eee;
}
#arrow{
position:fixed;
}
#first{
background-color: red;
}
#second{
background-color:green;
}
#third{
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="arrow">
<a class="next">next</a>
<a class="previous">prev</a>
</div>
<section id="first">
...
</section>
<section id="second">
...
</section>
<section id="third">
...
</section>

Categories

Resources