Javascript add into history - javascript

I have an ajax based website & i have successfully added support for the back button, which works fine. My issue is that when i go back i can not go forward.
How can i add an a future item in history? Or enable the forward button?
Is there an event to manipulate the forward button?
history buttons
HASHBANG LIBRARY
function hashbang(pages){
this.currentPage = [];
this.currentPageIndex = 0;
this.displayer = true;
var that = this;
this.setup = function(){
N$(window).event('popstate', function(node, event){
console.log('pop');
document.body.style.display = "none";
that.displayer = false;
that.removeResources();
that.currentPageIndex++;
//var hash = (event.state)? event.state.page : window.location.hash.slice(1).replace('!','');
console.log(that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]);
if(pages[that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['src']]){
that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['params']['hash'] = '#!' + that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['params']['hash'];
that.changePage(that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['src'], that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['js'], that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['into'], that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['params'], true);
}
});
}
this.state = function(page_, update){
N$.ajax('../php/ajax/AJAX_BASE.php', 'post', {}, function(AJAX_BASE){//get base
if(window.history.pushState && window.history.replaceState){//compatibility check
if(!update){
if(window.history.state != null){
if(window.history.state.page != page_){// if page is not page_
window.history.pushState({page: page_}, '', AJAX_BASE+page_);//push page into history
}else{
try{
window.history.replaceState({page:page_}, '', AJAX_BASE+page_);
}catch(error){
}
}
}else{
window.history.pushState({page: page_}, '', AJAX_BASE+page_);
}
}else{
window.location.hash = '!'+page_;
}
}
}, true);
}
this.loadPage = function(src, func_array, into, params, prevent_push){
console.log('loadPage:::: ' + src);
if(typeof params != typeof {})
params = {};
if(params['hash'] == undefined){
params['hash'] = window.location.hash;
}else{
params['hash'] = params['hash'];
}
this.state(src + params['hash'], false);
params['hash'] = params['hash'].replace(/#!/g, "-").slice(1);
var mobile = ( (browser)?( (browser.loaded_mobile)? browser.loaded_mobile : false ): false);
N$.loadCSS(src + '_' + mobile + '.css', function(){
N$.ajax(src + '_' + mobile + '.php', 'POST',params, function(page_content){
N$(into).innerHTML(page_content);
if(func_array['initialize'])
func_array['initialize'](params);
console.log('attempted::' + src + '_' + mobile + '.js');
N$.loadJS(src + '_' + mobile + '.js', function(){
console.log('loaded::' + src + '_' + mobile + '.js');
if(func_array['execute'])
func_array['execute'](params);
});
if(func_array['terminate'])
func_array['terminate'](params);
if(!that.displayer)
document.body.style.display = "block";
}, false);
});
if(!prevent_push || prevent_push == undefined || prevent_push == null){
console.log('page pushed');
var pusher = {
'src': src,
'params': params,
'js': func_array,
'into': into
};
console.log(pusher);
that.currentPage.push(
pusher
);
}
}
this.loadPartial = function(src, func_array, into, params){
src = '/i/partials/' + src;
if(typeof params != typeof {})
params = {};
var mobile = ( (browser)?( (browser.loaded_mobile)? browser.loaded_mobile : false ): false);
N$.loadCSS(src + '_' + mobile + '.css', function(){
N$.ajax(src + '_' + mobile + '.php', 'POST',params, function(page_content){
N$(into).innerHTML(page_content);
if(func_array['initialize'])
func_array['initialize']();
N$.loadJS(src + '_' + mobile + '.js', function(){
if(func_array['execute'])
func_array['execute']();
});
if(func_array['terminate'])
func_array['terminate']();
}, false);
});
}
this.changePage = function(src, func_array, into, params, prevent_push){
console.log('changePage:::: ' + src);
document.body.style.display = "none";
this.displayer = false;
this.removeResources();
this.loadPage(src, func_array, into, params, prevent_push);
}
this.removeResources = function(){
var mobile = ( (browser)?( (browser.loaded_mobile)? browser.loaded_mobile : false ): false);
if(this.currentPage[this.currentPage.length - 1]){
N$.removeResource(this.currentPage[this.currentPage.length - 1]['src']+ '_' + mobile +'.css', N$.globals.loaded_css);
N$.removeResource(this.currentPage[this.currentPage.length - 1]['src']+ '_' + mobile +'.js', N$.globals.loaded_script);
}
}
}
This library works in adjacent to other libraries. My interest is on the popstate event

Related

jQuery function conversion

I've been working on this script that I am using with a WordPress plugin I wrote for our blogs at work. I'm stripping it down to make it a pure jQuery plugin but most of the questions I've seen where for getting the plugin to work like this:
$('.some-target').cta();
Whereas I want to write it so that the user can do something like:
cta();
or
$.cta
I'm not really getting clear answers or seeing many guides covering this, or really if it's possible. In the end I want it to work like it's original iteration for WP, but as a stand alone jQuery plugin for static sites:
cta({
text: "Some Text",
icon: "Some-icon.jpg",
dist: 50
});
Here is the original code:
jQuery(document).ready(function($){
cta = function(o) {
o = o || {};
var bgColor = o.bgColor;
var url = o.url;
var text = o.text;
var icon = o.icon;
var buttonText = o.buttonText;
var target = o.target;
var dist = o.dist;
if((o.icon != null) || o.icon == "" ) {
jQuery('body').append(
'<div class="cta-popup-wrapper with-icon"><div class="cta-popup"><span class="close-trigger">X</span><img class="cta-icon" src="' + icon + '" alt="Call to Action Icon"><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
} else {
jQuery('body').append(
'<div class="cta-popup-wrapper without-icon"><div class="cta-popup"><span class="close-trigger">X</span><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
}
if(target != null) {
var t = $(target);
if(t.length) {
$(window).scroll(function() {
var hT = t.offset().top,
hH = t.outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
} else {
if((dist != null) && (dist > 0)) {
var b = $('body').innerHeight();
dist = dist / 100;
var trigger = b * dist;
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (wS > trigger){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
}
}
});

why my ajax makes me to refresh my page to see content?

I want when my ajax detect changes on database automatically show the content in html without refresh , but it isnt doing nothing. I have to refresh the page , how can I fix it? I am trying to do ajax long polling
$(function(doc, win, $) {
var has_focus = true;
var notification = win.Notification || win.mozNotification || win.webkitNotification;
var $badge = $("#notifications-badge");
var $list = $("#notifications-list");
var $button = $("#notifications-button");
URL_GET_NOTIFICATION = BASE_URL + 'notify/pusher';
URL_GET_NOTIFICATION_UPDATE = BASE_URL + 'notify/update';
if ('undefined' === typeof notification) {
console.log('Web notification not supported');
} else {
notification.requestPermission(function(permission) {});
}
function check_notifications(timestamp) {
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
data: { timestamp : timestamp },
dataType: 'json',
async: true,
success: function (data) {
for (var i in data.notifications) {
notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
}
check_notifications(data.timestamp);
}
});
}
function notify(message, type, created_at) {
var type_txt = 'info';
var url = '#';
var icon = 'info-circle';
if (type == 0) {
type_txt = 'success';
icon = 'check';
} else if (type == 1) {
type_txt = 'info';
icon = 'exclamation';
} else if (type == 2) {
type_txt = 'warning';
icon = 'exclamation-triangle';
} else if (type == 3 || type == 4) {
type_txt = 'danger';
icon = 'fire';
}
$badge.show();
$badge.text(parseInt($badge.text()) + 1);
$list.find(".item").eq(13).nextAll(".item").remove();
var item = '<li class="item text-' + type_txt + '"><a href="' + url + '"><span class="text-' + type_txt + '">' +
'<i class="fa fa-' + icon + ' fa-fw"></i> ' + message.substr(0, 22) + '</span>' +
'<span class="pull-right text-muted small" data-time="' + created_at + '">X</span></a></li>' +
'<li class="item divider"></li>';
$list.prepend(item);
$('.dropdown.open .dropdown-toggle').dropdown('toggle');
return true;
}
$(win).on("blur", function () {
has_focus = false;
});
$(win).on("focus", function () {
has_focus = true;
});
$button.on("click", function () {
$badge.fadeOut(300, function () {
$badge.text(0);
});
$list.find("span[data-time]").each(function (index) {
var $this = $(this);
$this.text(moment.unix($this.data('time')).fromNow());
});
});
check_notifications();
}(document, window, jQuery));

Javascript url.location & replaced with?

I am having a language selection radio button in my html page and on selection of a language I make the call to the same url appending '?lang='. This I am doing via js and when the url is submitted the & is replaced with ?. Below is my js code.
function removeBookmarkFromUrl(url) {
var arr = url.split("#");
return arr[0];
}
$(document).ready(function () {
$('input:radio[name=lang]').change(function() {
var url = window.location.href;
var selectedLang = $(this).attr('id');
url = removeBookmarkFromUrl(url);
if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
var currentLang = url.slice(pos + 6, pos + 8);
if (url.charAt(pos) == '?') {
url = url.replace('?lang=' + currentLang, '?lang=' + selectedLang);
window.location = url;
} else if (url.charAt(pos) == '&') {
url = url.replace('&lang=' + currentLang, '&lang=' + selectedLang);
window.location = url;
}
} else {
if (url.indexOf('?') >= 0) {
window.location = url + '&lang=' + selectedLang;
} else {
window.location = url + '?lang=' + selectedLang;
}
}
});
});
Now when I make the language selection the url in the browser is http://localhost:8080/test/report.htm?count=40&name=jerry?lang=en. I debugged the code and saw url to be http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en but this is getting changed on submission.
Your code seems to be fine. You should consider to use functions, they make debugging a lot easier.
function removeBookmarkFromUrl(url) {
var arr = url.split("#");
return arr[0];
}
function getLangUrl(url, lang){
url = removeBookmarkFromUrl(url);
if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
var currentLang = url.slice(pos + 6, pos + 8);
if (url.charAt(pos) == '?') {
url = url.replace('?lang=' + currentLang, '?lang=' + lang);
return url;
}
else if (url.charAt(pos) == '&') {
url = url.replace('&lang=' + currentLang, '&lang=' + lang);
return url;
}
} else {
if (url.indexOf('?') >= 0) {
return url + '&lang=' + lang;
} else {
return url + '?lang=' + lang;
}
}
}
var url;
url = "http://localhost:8080/test/report.htm";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?count=40&name=jerry";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));

Run a JS function on page load

I know that this question has been asked multiple times, but my case is different. So I have an external JavaScript file which contains the code for my accordion menus (you know, the user clicks on a title and it expands). Now I want to get a # (hash sign) from the url and according to it to open a specific "accordion" onload.
So here's what I've tried:
<body onload="runAccordion(index);"> <!-- In the example bellow, index should be equal to 1 -->
But it never worked (as desired), because I don't know how to "read" the url's # (element's id)...
Here's the markup for an accordion:
<div id="AccordionContainer" class="AccordionContainer">
<div onclick="runAccordion(1);">
<div class="AccordionTitle" id="AccordionTitle1">
<p>Title</p>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent">
<p>
<!-- Content -->
</p>
</div>
Or maybe I should use PHP $_GET???
JS file contents:
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}
Give the following a try:
$(document).ready(function() {
var hash = window.location.hash;
hash = hash.length > 0 ? hash.substring(1);
if (hash.length) {
runAccordion(window.location.hash);
}
});
The above will grab your hash index out of the URL. To add a hash to the URL, try the following:
window.location.hash = 1; //or whatever your index is
# You can use: #
window.onload = function() {
runAccordion(window.location.hash);
}

using touchstart causes screen to become fuzzy on touchstart

I am currently testing touchstart functionality on my device (Samsung galaxy S2) for my game. I am programming using javascript and jquery wrapped under phonegap in android and currently having issues as follows:
my touch start event (e.g triggering an attack button "touchstart" event to run some javascript to perform the attack action) causes my screen to become temporarily fuzzy, then back to normal in less than a second, so more like a screen flicker where images become jittery). I am not using css transforms or transitions just plain css and images.
Can someone please let me know if they have encountered moreorless similar issues to mine. A bit at a loss whether it is a hardware or touchstart issue where i can solve that problem.
Sample Javascript below for my navigation controls (left, up, down, right touchstart tap):
if ('ontouchstart' in document.documentElement) {
var left = document.getElementById('left');
left.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var l_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var l_xy = l_oldCell.split('_');
var l_x = l_xy[0];
var l_y = l_xy[1];
if(l_y == 1)
{
direction = "left";
setCharDynamics(controlsPlayerChar);
return false;
}
var l_newCell = l_x + '_' + (parseInt(l_y) - 1);
// validate if next cell is empty
if($('#' + l_newCell + ':has(".shadow")').val() != undefined
|| $('#' + l_newCell + ':has(".ally")').val() != undefined
|| $('#' + l_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "left";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + l_newCell).append($('#' + controlsPlayerChar));
$('#' + l_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'left' and set next footstep
setDirection('left');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
var up = document.getElementById('up');
up.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var u_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var u_xy = u_oldCell.split('_');
var u_x = u_xy[0];
var u_y = u_xy[1];
if(u_x == 1)
{
direction = "up";
setCharDynamics(controlsPlayerChar);
return false;
}
var u_newCell = (parseInt(u_x) - 1) + '_' + u_y;
// validate if next cell is empty
if($('#' + u_newCell + ':has(".shadow")').val() != undefined
|| $('#' + u_newCell + ':has(".ally")').val() != undefined
|| $('#' + u_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "up";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + u_newCell).append($('#' + controlsPlayerChar));
$('#' + u_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'up' and set next footstep
setDirection('up');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
var down = document.getElementById('down');
down.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var d_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var d_xy = d_oldCell.split('_');
var d_x = d_xy[0];
var d_y = d_xy[1];
if(d_x == rows)
{
direction = "down";
setCharDynamics(controlsPlayerChar);
return false;
}
var d_newCell = (parseInt(d_x) + 1) + '_' + d_y;
// validate if next cell is empty
if($('#' + d_newCell + ':has(".shadow")').val() != undefined
|| $('#' + d_newCell + ':has(".ally")').val() != undefined
|| $('#' + d_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "down";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + d_newCell).append($('#' + controlsPlayerChar));
$('#' + d_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'down' and set next footstep
setDirection('down');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
var right = document.getElementById('right');
right.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var r_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var r_xy = r_oldCell.split('_');
var r_x = r_xy[0];
var r_y = r_xy[1];
if(r_y == cols)
{
direction = "right";
setCharDynamics(controlsPlayerChar);
return false;
}
var r_newCell = r_x + '_' + (parseInt(r_y) + 1);
// validate if next cell is empty
if($('#' + r_newCell + ':has(".shadow")').val() != undefined
|| $('#' + r_newCell + ':has(".ally")').val() != undefined
|| $('#' + r_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "right";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + r_newCell).append($('#' + controlsPlayerChar));
$('#' + r_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'right' and set next footstep
setDirection('right');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
}
Please let me know if you think anything is amiss with regards to above script. The way I add the touchstart event is the same in other areas of my script when e.g to launch an attack or launch an options menu for instance.
Seems that this is tap highlighting.
You can try to disable this effect applying -webkit-tap-highlight-color CSS property on your controls or disable this in all elements using * selector.
For example:
.someelement {
-webkit-tap-highlight-color: transparent;
}
We've ran into this issue when using translate3d transformations.
We fixed it by setting
* { -webkit-transform: translate3d(0,0,0,); }
so that every element is initialized for the 3d space
First of all, make sure you are calling preventDefault() on the event. I've noticed that if you are targeting mouse events as well, they can fire on touch. Otherwise, I use a slightly different method of disabling touch highlighting. Try:
-webkit-tap-highlight-color: rgba(0,0,0,0);
In the css for your button.

Categories

Resources