Please Guys i need assist with this project:
I am a bit confused rn, i wanted this piece of code to display a specific styled div modal designed for a specific browser. What i want is: if browser is firefox modal displays "On My Way Home", styled with a class .home. else if my browser is chrome, display a modal "Home Now"
Thanks
$(function(){
function modal() {
var options = {
trigger: '.lp-download-btn',
selectorClose: '.close',
selectorContent: '#j-download-instructions',
selectorLinks: 'a',
chromes: '.chrome'
};
var $body = $(options.selectorContent);
var $chromeBrowser = $(options.chromes);
$('body').on('click', options.trigger, function() {
$body.css({
height: '100%',
width: '100%',
visibility: 'visible'
});
})
$body.on('click', function(e){
if (this == e.target) {
$body.hide();
return false;
}
});
$body.on('click', options.selectorClose, function(){
$body.hide();
return false;
});
$body.on('click', function() {
$chromeBrowser.css({
display: 'block'
})
})
}
function browserDetection() {
// IE or not
if (navigator.userAgent.search("MSIE") >=0 ){
return modal();
}
// Chrome browser
else if (navigator.userAgent.search("Chrome") >= 0) {
return modal();
}
// Firefox Browser
else if (navigator.userAgent.search("Firefox") >= 0) {}
// Safari browser
else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {}
// Opera browser
else if (navigator.userAgent.search("Opera") >= 0) {}
}
browserDetection();
});
You can perform user agent sniffing to possibly detect which browser someone is in, although it does have drawbacks https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent but in this case you can use that to do what you would like.
Related
In my scenario the code should prevent the the default scroll event and use scrollIntoView() to move the user to a specific section according to the scroll direction.
https://stackoverflow.com/a/4770179/9164633 I used this method to prevent the scroll default event.
And I detect the direction like so,
preventDefault(e) {
e.preventDefault();
if(this.waiting == false && this.forceInitialScroll != true) {
if(e.deltaY && e.deltaY > 7) {
this.scrollDirection = 'down';
this.checkScroll()
}else if(e.deltaY && e.deltaY < -7) {
this.scrollDirection = 'up';
this.checkScroll()
}else {
}
}
},
and Im pretty sure that both are working fine.
After preventing the scroll and detecting the scroll direction I try to scroll the user to the section like so,
checkScroll() {
let element;
if(this.scrollDirection == 'down' && this.scrollIndex != 4 ) {
element = document.getElementById(`section-${this.scrollIndex+1}`);
}else if(this.scrollDirection == 'up' && this.scrollIndex != 0) {
element = document.getElementById(`section-${this.scrollIndex-1}`);
}
this.waiting = true;
if(element) {
console.log(element)
element.scrollIntoView({
behavior: 'smooth',
block: 'center',
})
}
setTimeout(() => {
if(this.waiting == true) {
this.waiting = false;
this.scrollDirection = null;
}
}, 450)
},
this.waiting is used to prevent the user form scrolling more than one section at a time.
On firefox the browser doesnt scroll the user properly though its working fine on chrome.
Apparently Firefox's behavior with event.preventDefault() was that it blocked any kind of user scrolling and even the js manual scrolling.
The problem in my case was solved by hiding the scroll in css instead of js by using overflow: hidden; and then controlling the scroll manually instead of preventing the default behavior.
I'm trying to run a small piece of jQuery - when it's clicked it runs a function and when clicked again it runs another.
I have tried the following but this doesn't even run the first.
$('body').on('click', '.card--small', function() {
console.log('clicked');
$(this).addClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
}, function() {
console.log('clicked again');
$(this).removeClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
});
function topCheck() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
console.log('Chrome');
} else {
return 'safari';
console.log('Safari');
}
}
}
Just use the card--expanded class as a flag to determine which click you need and design your function accordingly.
$('body').on('click', '.card--small', function (e) {
var self = $(this),
isExpanded = self.hasClass('card--expanded'),
isChrome = topCheck() === 'chrome'; // will always be false as topCheck never returns 'chrome' (it returns either 'safari' or undefined).
self.toggleClass('card--expanded', !isExpanded);
if (!isExpanded) {
console.log('clicked');
if (isChrome) { // will never execute as isChrome will always be false
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
} else {
console.log('clicked again');
if (isChrome) { // will never execute as isChrome will always be false
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
}
});
The point is to use some external condition as a flag to keep track of the click state. This could be a global variable, or a local variable above your handler in the scope chain (or a CSS class, or a HTML5 data attribute, etc.). There are a number of ways to do this. Using a CSS class seems like a natural fit in your case.
Also, the topCheck function would be better written if there were a chance it could return 'chrome':
function topCheck() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') > -1) {
if (ua.indexOf('chrome') > -1) {
return 'chrome';
console.log('Chrome');
} else {
return 'safari';
console.log('Safari');
}
}
}
or
function topCheck() {
var ua = navigator.userAgent.toLowerCase(),
browser = 'unknown';
if (ua.indexOf('safari') > -1) {
if (ua.indexOf('chrome') > -1) {
browser = 'chrome';
console.log('Chrome');
} else {
browser = 'safari';
console.log('Safari');
}
}
return browser;
}
Personally, I dislike multiple return statements per function so I would use the second form.
$('.card--small').click( function(){
// run function 1
function_1();
$(this).unbind('click').click( function(){
// run function 2
function_2();
});
});
Inside function 2 you would have to rebind $('.card--small') to run function 1 on click, if you want to run function 1 again.
A simple approach without jQuery. Just keep some kind of state around to determine what to do.
<html>
<head>
<style>
div {
background-color: #ff0;
}
</style>
<script>
var state = 0;
function runIt() {
if (state > 0) {
doSomethingDifferent();
state = 0;
return;
}
doSomething();
state = 1;
}
function doSomething() {
alert("something");
}
function doSomethingDifferent() {
alert("something different");
}
</script>
</head>
<body>
<div onClick="runIt()">Click me</div>
</body>
</html>
Another approach would be to rebind the click event to another function.
In your function topCheck nothing is returned when you detect Chrome. You only log it. Your click event calls the function topCheck but does not get anything back from the function when Chrome is detected. So your if statement probably gets an undefined value.
To answer your original question on how to toggle function called on click, your code should look something like this:
function click1() {
// ...
$(this).off('click', click1).on('click', click2)
}
function click2() {
// ...
$(this).off('click', click2).on('click', click1)
}
$('#link').on('click', click1)
Live demo
But from your code snippet it seems that it would be simpler to implement toggling in single function:
$('body').on('click', '.card--small', function() {
if (!$(this).hasClass('card--expanded') {
$(this).addClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
} else {
$(this).removeClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
}
});
Try
css
.card--small__container {
top:0px;
display:block;
position:relative;
}
js
$("body")
.on("click", ".card--small", function () {
if (topCheck() == "Chrome"
&& !$(this).data("clicked")
&& !$(this).hasClass("card--expanded")) {
$(this).data("clicked", true)
.addClass("card--expanded")
.css("top", "51px");
} else if ( !! $(this).data("clicked")
&& $(this).hasClass("card--expanded")) {
$(".card--small")
.css("top", "0")
.removeClass("card--expanded");
}
});
function topCheck() {
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("chrome") !== -1 ? "Chrome" : "Safari"
};
http://jsfiddle.net/o4ebav8t/
I am trying to run some code when the browser back button is clicked.
How can i found out browser's back button with out changing the browser history?
I tried the code below.
I got an exception in the else block saying: "event is not defined".
window.onunload = HandleBackFunctionality();
function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked…");
} else {
alert("Browser refresh button is clicked…");
}
} else {
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked…");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked…");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
use
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
});
Okay. Besides the fact that you should not initially trigger the event and to .unload = FunctionName and not .unload=FunctionName() and that you need to pass the event-argument I checked the code in the browser.
currentTarget is empty - this totally makes sense as there is no event-target like onclick but it is just the site reloading/unloading.
Please debug the code by yourself by using this and fit it to your needs:
window.onunload = HandleBackFunctionality;
function HandleBackFunctionality(event)
{
console.log(event, window.event);
}
You will see that currentTarget is not set (while event is).
This is the only solution that works for me with IOS safari.
<script>
window.addEventListener( "pageshow", function ( event ) {
var pagehistory = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( pagehistory ) {
// back button event - Do whatever.
}
});
</script>
I have 3 buttons with hover states which makes a little tooltip appear to describe the button. They work fine but on touchs screen they do not disappear after the user clicks on the button.
So I've tried a few js scripts for checking if a device is a touch device or not. They almost work but they also when I test on IE11 it also gets detected as a touch device. Chrome & Firefox do not get mistaken as a touch device.
Any sugestions?
Her is what I've tried
/*****************************
TOUCH DEVICES HOVER FIX START
****************************/
// http://stackoverflow.com/a/4819886/1814446
function isTouchDevice() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
};
// http://www.stucox.com/blog/you-cant-detect-a-touchscreen/#poke-it
var hasTouch;
window.addEventListener('touchstart', function setHasTouch () {
hasTouch = true;
// Remove event listener once fired, otherwise it'll kill scrolling
// performance
window.removeEventListener('touchstart', setHasTouch);
}, false);
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
define(['Modernizr', 'prefixes', 'testStyles'], function( Modernizr, prefixes, testStyles ) {
// Chrome (desktop) used to lie about its support on this, but that has since been rectified: http://crbug.com/36415
Modernizr.addTest('touchevents', function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
var query = ['#media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
testStyles(query, function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
});
});
if(bool===true) {
console.log('Touch Device'); //your logic for touch device
jQ( "#btn-1, #btn-2, #btn-3" ).click(function() {
jQ("#btn-1 .tooltip").css('opacity', '0');
jQ("#btn-2 .tooltip").css('opacity', '0');
jQ("#btn-3 .tooltip").css('opacity', '0');
});
}
else {
//your logic for non touch device
}
For IE10+ you can utilize "window.navigator.msMaxTouchPoints"
example code
function isIETouch ()
{
return window.navigator.msMaxTouchPoints == undefined ? false : window.navigator.msMaxTouchPoints;
}
I have this javascript code to detect fields changes on a page. It is working well with IE but unfortunately not in chrome. I really don't know why this is happening. When I try to access it via different browsers and units. This javascript is not working well. I need to clear my cache history to make it work properly. Here's the code:
var ctr = 1;
var isFirstLoad = true;
function propertyChangedByCode() {
ctr = 0;
propertyChanged();
}
function propertyChanged() {
if (document.readyState == "complete") {
$('[id$=SaveButton]').removeAttr("disabled");
$('[id$=SaveButton]').removeAttr("class");
$('[id$=SaveButton]').addClass("btn btn-primary");
warnMessage = 'Warning: You have unsaved changes.';
console.log(ctr);
window.onbeforeunload = function () {
if (ctr == 0) {
return warnMessage
}
else if (ctr == 1) {
ctr = 0;
}
}
}
}
$("body").click(function (event) {
console.log(event.target);
if (event.target.type == "submit" && event.target.value != "Save" && event.target.value != "Cancel" && event.target.value != "Next") {
ctr = 0;
propertyChanged();
console.log("BODY clicked");
}
});
function pageLoad() {
jQuery("input.datepicker").dp({
dateFormat: 'M d, yy',
altFormat: 'yy-mm-dd',
buttonText: '<i class="icon icon-calendar"></i>',
showOn: 'both'
});
$("button.ui-datepicker-trigger").addClass('btn right');
console.log("PageOnLoad: " + ctr);
var warnMessage = 'Warning: You have unsaved changes.';
$('input[type="text"],select,textarea').each(function (k, v) {
var elem = $(this);
// Save current value of element
elem.data('oldVal', elem.val());
// Look for changes in the value
elem.bind("change keyup input paste", function (event) {
ctr = 0;
// If value has changed...
if (elem.data('oldVal') != elem.val()) {
propertyChanged();
}
});
});
$('.btn').click(function (e) {
console.log("whatever");
ctr = 1;
});
//ui-datepicker-trigger
$('.ui-datepicker-trigger').click(function (e) {
console.log("date");
ctr = 0;
});
if (isFirstLoad) {
window.onbeforeunload = null;
$('[id$=SaveButton]').attr("disabled", "disabled")
console.log("Disable");
isFirstLoad = false;
}
So with this, I decided to take on the path on disabling caching on my system. I put this code on my master page page_load.
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache)
Response.Cache.SetNoStore()
Response.Cache.SetAllowResponseInBrowserHistory(True)
Base on my research, these 3 lines will disable caching in my application. Tried to clear my cache, inputted some values on my field, hit save, and browse again to that page but still the fields are presenting my previous input in the autofill. So I'm assuming the disabling of caching won't work. Do you have any ideas why the disabling of caching is not workin? Do you have any suggestions regarding browsing caching? And why do you think I'm experiencing this issues that I need to clear my cache in order to make my javascript work properly? Lastly, why is it working on my IE but not in chrome? Thanks! Sorry for the load of questions.