Modify javascript to open in a new window (window.location.href) - javascript

I'm creating a site for a client who needs to use a zip code to search for a provider but the search is on a provider search website that's not within our domain. I need to modify this script to be able to force it to open in a new window.
<script type="text/javascript">
$(document).ready(function () {
var submitVetSearchD = function () {
submitVetSearch($('#zip'));
}
function submitVetSearchM() {
submitVetSearch($('#zipM'));
}
function submitVetSearchF() {
submitVetSearch($('#zipF'));
}
function submitVetSearch(ele) {
var zipval = ele.val();
var url = 'https://www.fakesearchresultswebsite.com/';
if (zipval !== "") {
return window.location.href = url + '?zip=' + zipval;
}
}
$("#zip").keyup(function (event) {
if (event.keyCode == 13) {
submitVetSearchD();
}
});
$('#large-header-vet-search').click(submitVetSearchD);
$("#zipM").keyup(function (event) {
if (event.keyCode == 13) {
submitVetSearchM();
}
});
$('#mob-vet-search').click(submitVetSearchM);
$("#zipF").keyup(function (event) {
if (event.keyCode == 13) {
submitVetSearchF();
}
});
$('#footer-vet-search').click(submitVetSearchF);
$("a[rel^='prettyPhoto']").prettyPhoto();
//top menu size
$(window).resize(function () {
setTopMenuHeight();
});
setTopMenuHeight();
var smallHeader = false;
var menuBig = true;
$(document).scroll(function () {
var ele = $("#top-menu-height");
var menuBigNew = !(ele.is(":visible") && $(window).scrollTop() > 200);
if (menuBig != menuBigNew && smallHeader) {
menuBig = menuBigNew;
$("#navtop").toggleClass("small-page-header");
$(".fixed-top").toggleClass("pos-fix");
$("#page-header").toggleClass("fixed-header");
$("#title-area").toggleClass("title-area-small");
$("#logo1").finish();
$("#logo2").finish();
$("#top-menu").finish();
if (menuBig) {
$("#logo2").toggle();
$("#logo1").toggle(1000);
} else {
$("#logo1").toggle();
$("#logo2").toggle(1000);
}
//$("#top-menu").fadeToggle();
}
});
//$('body').on('open.fndtn.reveal', function(){
// $('body').css('overflow', 'hidden');
//});
//$('body').on('closed.fndtn.reveal', function(){
// $('body').css('overflow', 'visible');
//});
});
function setTopMenuHeight() {
var ele = $("#top-menu-height");
var height = $("#page-header").height();
ele.height(height);
}
</script>

Replace
return window.location.href = url + '?zip=' + zipval;
with
var newWin = window.open(url + '?zip=' + zipval);
return true;
Declare newWin in the global scope, it will reference the new window.
Reference: http://www.w3schools.com/jsref/met_win_open.asp

Related

Closing a menu on anywhere click

I am working on a website and here is the link file:///D:/fahim/HTML/menu/index.html. If you click the menu its closing on its own "X" button, but i want it to close by clicking outside the menu. This is the javascript used on the home page.
<script>
var popupView = new popup();
document.querySelector('#btn_1').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_1'));
});
document.querySelector('#btn_2').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_2'), function () {
console.log('show do something');
});
});
document.querySelector('#btn_3').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_3'), '', function () {
console.log('CLOSE');
});
});
</script>
And this is the code which is attached as popup_view.js file on server
(function () {
var popup = function() {
function hide(dom, dosomething) {
if (!dom) {
console.error('hide function not set dom object');
return;
}
if (dosomething) {
dosomething();
}
dom.className += ' ' + 'popup_hide';
}
function show(dom, dosomethingShow, dosomethingClose) {
if (!dom) {
console.error('show function not set dom object');
return;
}
if (dosomethingShow) {
dosomethingShow();
}
var className = 'popup_hide',
reg = new RegExp('(^|\\b)' +
className.split(' ').join('|') +
'(\\b|$)', 'gi');
dom.className = dom.className.replace(reg, '').trim();
var nodes = dom.childNodes;
for (var i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].className === 'pop_up_close') {
var close = function (e) {
if (dosomethingClose) {
dosomethingClose();
}
dom.className += ' ' + 'popup_hide';
nodes[i].removeEventListener('click', close);
};
nodes[i].addEventListener('click', close);
break;
}
}
}
this.show = show;
this.hide = hide;
};
window.popup = popup;
})();
Please help as i have tried lot of codes except these but non of them works
$(document).on('click', function(e){
//your close function
e.stopPropagation();
}
Put that code anywhere in your $(document).ready(... block

Why function(document) doesn't work in separate file?

I have an HTML file and this contain JavaScript code and works fine, but when I decided put the JS code in different file and call from the HTML file, doesn't work. Why?
The JS code is like this:
(function (document) {
var toggleDocumentationMenu = function () {
var navBtn = document.querySelector('.main-nav1');
var navList = document.querySelector('.main-nav2');
var navIsOpenedClass = 'nav-is-opened';
var navListIsOpened = false;
navBtn.addEventListener('click', function (event) {
event.preventDefault();
if (!navListIsOpened) {
addClass(navList, navIsOpenedClass);
navListIsOpened = true;
} else {
removeClass(navList, navIsOpenedClass);
navListIsOpened = false;
}
});
};
var toggleMainNav = function () {
var documentationItem = document.querySelector('.main-nav3');
var documentationLink = document.querySelector('.main-nav3 > .main-sub-nav');
var documentationIsOpenedClass = 'subnav-is-opened';
var documentationIsOpened = false;
if (documentationLink) {
documentationLink.addEventListener('click', function (event) {
event.preventDefault();
if (!documentationIsOpened) {
documentationIsOpened = true;
addClass(documentationItem, documentationIsOpenedClass);
} else {
documentationIsOpened = false;
removeClass(documentationItem, documentationIsOpenedClass);
}
});
}
};
var isTouch = function () {
return ('ontouchstart' in window) ||
window.DocumentTouch && document instanceof DocumentTouch;
};
var addClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(/\s+$/gi, '') + ' ' + className;
};
var removeClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(className, '');
};
toggleDocumentationMenu();
toggleMainNav();
})(document);
I read it's possible that works if I put like this:
$(document).ready(function() {
// the javascript code here
});
But it still doesn't working.
Now I wonder, It's possible this code works fine in separate file?

Use google analytics to capture touch events in a slider?

So I been trying to track mobile swipes where inside the slider there is other swipes. Look the image below. The code you see attached is part of my Google Analytics events tracking code.
Here is my code:
// Shop buttons
jQuery('.shop-btn-group a').click(function(event) {
var clickedLink = jQuery(this);
var gaqArgs = ['_trackEvent', 'Shop'];
var validShopLink = false;
if ( clickedLink.hasClass('shop-women') ) {
validShopLink = true;
gaqArgs.push('Click-Shop');
}
if (this.rel) {
gaqArgs.push(this.rel);
}
if (validShopLink) {
// Check if the user is using a keyboard command to open the link in a new tab
if (event.metaKey || event.ctrlKey || event.shiftKey) {
try {
_gaq.push(gaqArgs);
}
catch(err) {}
return;
}
else {
event.preventDefault();
try {
_gaq.push(gaqArgs);
_gaq.push(function() {
document.location = clickedLink[0].href;
});
}
catch(err) {
document.location = this.href;
}
}
}
});
// Product click
jQuery('.image-wrap a').click(function(event) {
var clickedLink = jQuery(this);
var gaqArgs = ['_trackEvent', 'Shop'];
var validShopLink = false;
if ( clickedLink.hasClass('frame-image') ) {
validShopLink = true;
gaqArgs.push('Click-Product');
}
if (this.rel) {
gaqArgs.push(this.rel);
}
if (validShopLink) {
// Check if the user is using a keyboard command to open the link in a new tab
if (event.metaKey || event.ctrlKey || event.shiftKey) {
try {
_gaq.push(gaqArgs);
}
catch(err) {}
return;
}
else {
event.preventDefault();
try {
_gaq.push(gaqArgs);
_gaq.push(function() {
document.location = clickedLink[0].href;
});
}
catch(err) {
document.location = this.href;
}
}
}
});
// Color dots
jQuery('.color-dots .dot').click(function(event) {
var dot = jQuery(this);
var colorIndex = dot.index();
var sku = null;
try {
var link = dot.closest('.color-dots')
.siblings('.btn-wrapper')
.eq(0)
.find('.shop-btn-group')
.eq(colorIndex)
.children('a')
.eq(0);
if ( link[0].rel ) {
sku = link[0].rel;
}
}
catch(err) {}
if (sku) {
try {
_gaq.push(['_trackEvent', 'Shop', 'Click-Color', sku]);
}
catch(err) {}
}
});
Any help will be awesome thanks in advance.

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

Manually calling PDFJS functions. What func to call after PDFView.open to render

CanĀ“t find in the documentation what to do next.
Calling:
PDFView.open('/MyPDFs/Pdf1.pdf', 'auto', null)
I am able to see the blank pages, the loader and also the document gets the number of pages of my PDF.
The only thing is missing is the rendering.
Does anyone knows what I should call next?
Thanks
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call! Thanks
In viewer.js I added call to updateViewarea() after the document was downloaded.
... PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
updateViewarea();
}, ...

Categories

Resources