Can't find storyboards using Ajax - javascript

Hey you all.
var $storyboards; // This is the wrapper were all stroy boards are.
// Listen to URL changes when clicking the back or forward buttons in the browser.
window.onpopstate = function(event) {
LoadPage(document.location.pathname, !history.state || stateCount > history.state.stateCount);
};
var stateCount = 0;
$( document).ready(function() {
$storyboards = $('#storyboards');
$('.storyboard').attr('data-url', location.pathname);
setTimeout(function(){
$('body').addClass('splash-screen-hidden');
}, 3000);
$(document).on('mouseover mouseout','#menu a', function(e){
$('#menu a').not(this).toggleClass('toggle');
}).on('click', '#menu a', function(e){
if(e.metaKey || e.ctrlKey) return;
// Listen to the click event on the a tags in the menu
// Prevent the default behavior so the browser doesn't load the page.
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
var title = $this.attr('title');
NavigateToPage(url, title);
})
});
function LoadPage(url, back){
var $all_storyboard = $('.storyboard'); // This is all the storyboards we have in the page.
var $storyboard = $all_storyboard.filter('[data-url="' + url + '"]');
var storyboard_exists = $storyboard.length > 0;
PreparePageForLoad();
if(storyboard_exists)
StoryboardIsLoaded($storyboard.hide());
else {
console.log("we do not have the storyboard.. go load it!");
$.ajax({
url: url,
success: function(data){
$storyboard = $('.storyboard', data);
$storyboard.attr('data-url', url);
$storyboards.append($storyboard);
StoryboardIsLoaded($storyboard.hide());
},
error: function(){
alert('Oops! We could not load this page!.');
GoToRoot();
}
})
}
}
I really have a huge problem since I have to deliver my website project tomorrow morning and right now it's not working very well.
The real problem is I'm having trouble with loading between my pages. I'm using storyboard and ajax to switch out the code/content in the HTML without making a page load. So I get these sweet smooth transition between my pages.
I tested it on my own server and domain and it all works fine, but because I have to deliver the project/folder on another server the shit won't work. The main reason is that I have to put it all in a folder on the server and it's messing up the root navigation.
When I click on the link it goes: http://websitename.com/html-document/
But it should be: http://websitename/myfolder/html-document/
So the problem is it's going out of my folder and looking for the HTML document outside my folder instead of looking at it.
Here is the link to the website: http://franklyone.com/sylvester-svend/
Thanks in advance - Love

Related

Firefox - website takes me to new tab automatically and I cannot stop it

So I have a website where I can select links and click a button to open them all at the same time. When I do that Firefox takes me to one of the newly opened links automatically.
I wanted to stop this behavior, so I looked and looked, and eventually found this option:
browser.tabs.loadDivertedInBackground
Now, when I set this to true, newly opened tabs never automatically take me to them. So if I click an ad on a site that normally opens in a new tab and takes me to it, now it doesn't happen. I also tried this code:
<p><a href="#" onclick="window.open('http://google.com');
window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
This code opens 2 links at the same time. I was thinking maybe opening multiple links at the same time somehow overrides Firefox. But no, the links opened and I was not automatically taken to any of the new tabs.
Also must be said that I'm having this problem in Firefox 75 and 74. But when I try it in Firefox 55.0.2, I don't have the problem. In Firefox 55.0.2 the "browser.tabs.loadDivertedInBackground" actually works even on the website where I have the problem (I can't share the site because it's behind login).
This appears to be the code responsible to open multiple links on the website I have an issue with:
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
var win = window.open(t.data('link'), '_blank');
if (win) {
win.focus();
} else {
bootbox.alert('Please allow popups for this website');
}
}
});
So I tried everything I could think of. Many changes to the about:config, restarting my browser, unticking the "When you open a link in a new tab, switch to it immediately" option in Firefox. But nothing works. When I open links from this one site using this specific button, I always get automatically taken to one of the newly opened tabs.
Here is a similar-ish problem - https://www.reddit.com/r/firefox/comments/bnu6qq/opening_new_tab_problem/
Any ideas why this happens and how to fix it? I mean, a website shouldn't be able or allowed to override Firefoxe's native setting, right?
Okay, because I don't wanna be an ass, here is the solution.
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get().reverse()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
// var win = window.open(t.data('link'), '_blank');
setTimeout(() => window.open(t.data('link'), '_blank'),1000);
// if (win) {
// win.focus();
// } else {
// bootbox.alert('Please allow popups for this website');
// }
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
Basically, adding a "setTimeout" fixed it. For some reason Firefox needed the delay to process things correctly, I guess, I think. Before the delay, the actions would happen instantly, and I'll just guess that Firefox couldn't "catch up" to it in order to apply the exemption of not navigating to new tabs. But a timeout delay fixed it.
And for anyone that may run into this with a similar issue, it also required an edit in Firefox in "about:config" to set this to True.
browser.tabs.loadDivertedInBackground
That's all folks :)

ajax image viewer , back button and history - missing html and css

I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});

Using JavaScript's history.pushState with Angular's $location.search()

Before I get into the long-winded explanation and the code, let me just say that I understand that my implementation of this system is a bit of a hack-job. The goal was to implement a linking feature on a SPA application without completely overhauling what was already done with Angular and the Bootstrap modals. I'll wager that I probably could have accomplished something better with directives, but my understanding of directives is lacking.
The following is a function that is launched when the system detects a change in the URL. The new URL parameters are passed and are used to query the back-end for content.
function handleUrlParamsModalLaunch(data) {
/*Ensure modal is not displaying any data*/
vm.modalData = {};
vm.selectedTab = null;
/*Show modal loading gif*/
vm.isModalLoading = true;
$("#contentPartModal").modal();
/*Call the content service to return the clicked content article*/
contentpartservice.getContentItem(data.id, data.type).then(function (contentItem) {
if (contentItem) {
vm.isModalLoading = false;
vm.modalData = contentItem;
return;
} else {
closeModal("#contentPartModal").then(function () {
vm.isModalLoading = false;
logger.error('An error occurred while fetching content');
});
return;
}
}, function (error) {
closeModal("#contentPartModal").then(function () {
vm.isModalLoading = false;
logger.error('An error occurred while fetching content');
});
return;
});
}
The following function is run when a link is clicked. It adds the parameters needed to retrieve content from the back-end to the URL.
function setUrl(contentId, contentType) {
var urlParams = $location.search();
if (urlParams.q) {
$location.search({ q: urlParams.q, type: contentType, id: contentId });
} else {
$location.search({ type: contentType, id: contentId });
}
return;
}
The following is where the solution starts to look like a hack job. I need to remove the parameters from the URL when the modal closes, but I couldn't find a way to catch the Bootstrap modal close event from the scope of my Angular controller (where the above functions are being called). Instead, I wrote the following JavaScript code in script tags that does it without Angular's $location dependency.
<script>
/*
* Detect the closing of a modal window and modify the URL to no longer display linking information.
* Not handled in Angular because Angular lacks a suitable way to detect a bootstrap modal close.
*/
$('#contentPartModal').on('hidden.bs.modal', function () {
var pageUrl = $.url();
var pageParams = pageUrl.param();
if (pageParams.q) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?q=' + pageParams.q;
window.history.pushState({ path: newurl }, '', newurl);
}
} else {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({ path: newurl }, '', newurl);
}
}
});
</script>
Here is the resulting bug. The first time you click on a link, all of these functions run fine. The modal is opened with the correct data being displayed. When you close the modal, the URL parameters are removed from view. When you go to click on another link, the setUrl function is called, but the URL doesn't actually change. This results in the modal pop-up not opening. A second click on any link, and everything works as expected. The resulting bug is that each link needs to be clicked twice after the first time the modal has been opened.
Any hints to the cause of this bug would be much appreciated. I'd also accept an idea for a better implementation that would help me circumvent the issue altogether.
Thanks,
Matt

AJAX loading a page without reload

I am trying to load content from a new page using AJAX. The test website I am working on is dev.dog-company.com.
This is my code:
$('a[rel="load"]').click(function(){
//var siteurl = "";
var link = $(this).attr("href");
$(this).attr("href", '#');
$('#slider-wrapper').slideUp();
$('#content').wrap('<div id="wrap"></div>').css('opacity', '0.75').css('background-color', 'black');
$.ajax({
type: 'POST',
url: link,
success : function(data){
var response = $(data);
var head= response.find('head');
var slider = response.find('#slider-wrapper');
var content = response.find('#content');
$('#content').unwrap('<div id="wrap"></div>')
jQuery("head").html(head);
if(slider != null)
jQuery("#slider-wrapper").html(slider).slideDown();
jQuery("#content").html(content);
return false;
}
$(this).attr("href", link);
})
});
I am trying load the content on click but the page reload everytime without the click working. Also I am not sure if I need to be doing something else other than what I am doing to my code. The rel="load" is only on home, info->AboutUs & FAQ.
Your help is appreciated.
Update:
I still can't get it to work. This is my latest code. And the site is still running it. When i use the debugging for chrome it never goes through my code. is it the re="load" that is causing the problem?
Update:
My initial problem was not having the document ready. But not I think the way I am parsing the information isn't working. I tried find and filter both seem to not work correctly. Also how do I change the url in the browser after I it pushes the post.
Update
After a lot of messing around with it I got it to partially work. One thing I can't do it replace head. and then the data pushed in slider is there but it does not seem to work on the website. It doesn't slide down like I have it in the code.
$('document').ready(function() {
$('a[rel="load"]').click(function(e){
//var siteurl = "";
e.preventDefault();
var link = $(this).attr("href");
$('#slider-wrapper').slideUp();
$('#content').wrap('<div id="wrap-overlay"></div>');
/*$('#wrap').css({
'opacity': '0.75',
'background-color': 'black',
'z-index' : '10'
});*/
$.ajax({
//ajax setting
type: 'POST',
url: link,
dataType: 'html',
success : function(data){
//parse data
var response = $("<div>").html(data);
console.log(typeof(response));
console.log(response);
//var head = response.find('<head>').html();
slider = response.find('#slider-wrapper').html();
var content = response.find('#content').html();
console.log(content);
//console.log(head);
//console.log(slider);
//Post data
$('#content').unwrap();
//jQuery("head").empty().append(head);
if(slider != null){
jQuery("#slider-wrapper").empty().slideDown().append(slider);
}
jQuery("#content").empty().append(content);
return false;
}
})
});
});
Try this:
$('a[rel="load"]').click(function(e) {
e.preventDefault();
// ...
});
You need to stop default browser behaviour on link click, which is following it.

Showing warning with timeout when opening external links

I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}

Categories

Resources