changing page title on back button with jQuery Address - javascript

Utilizing jQuery Address to enable the browser's back button, I was able to leverage the plugin's event "onExternalChange" to detect when the browser actually hits the back button, so that I could trigger the page title to change on that as well. Unfortunately I can't get it to grab the current section, as it grabs it before it jumps, thus being one off everytime:
$.address.externalChange(function() {
var lastPageTitle = 'Kevin Dare Foundation | ' + $('nav').find('.active').html();
$.address.title(lastPageTitle);
});
link: http://nickdimatteo.com/kjd

Looks like the following solves the problem:
//Change Page Title on browser back button press
$.address.externalChange(function() {
var hash = document.location.hash.replace(/^#\//, '');
var lastPageTitle = 'Kevin Dare Foundation | ' + $('nav a[href="#'+hash+'"]').html();
if(hash) {
$.address.title(lastPageTitle);
}
else //account for no hash
{
$.address.title('Kevin Dare Foundation');
}
});

Related

How to use cookies to make a certain window only need to be displayed once when you log in again [duplicate]

There have already been answers to this question but I am still unsure exactly how it works.
I am using the following HTML in my footer.php:
<div id="popup">
<div>
<div id="popup-close">X</div>
<h2>Content Goes Here</h2>
</div>
</div>
and the following Javascript:
$j(document).ready(function() {
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
});
Everything works great, but I want to only show the pop up once per user (maybe using the cookie thing all the forum posts go on about) but I do not know exactly how to incorporate it into the JS above.
I know that I will have to load the cookie JS in my footer with this:
<script type="text/javascript" src="scripts/jquery.cookies.2.2.0.min.js"></script>
But that is all I understand, can anyone tell me exactly how the JS/jQuery should look with the cookie stuff added?
Thanks
James
*Note : This will show popup once per browser as the data is stored in browser memory.
Try HTML localStorage.
Methods :
localStorage.getItem('key');
localStorage.setItem('key','value');
$j(document).ready(function() {
if(localStorage.getItem('popState') != 'shown'){
$j('#popup').delay(2000).fadeIn();
localStorage.setItem('popState','shown')
}
$j('#popup-close, #popup').click(function() // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hidden.
});
});
Working Demo
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
You could get around this issue using php. You only echo out the code for the popup on first page load.
The other way... Is to set a cookie which is basically a file that sits in your browser and contains some kind of data. On the first page load you would create a cookie. Then every page after that you check if your cookie is set. If it is set do not display the pop up. However if its not set set the cookie and display the popup.
Pseudo code:
if(cookie_is_not_set) {
show_pop_up;
set_cookie;
}
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
You can use removeItem() class of localStorage to destroy that key on browser close with:
window.onbeforeunload = function{
localStorage.removeItem('your key');
};
The code to show only one time the popup (Bootstrap Modal in the case) :
modal.js
$(document).ready(function() {
if (Cookies('pop') == null) {
$('#ModalIdName').modal('show');
Cookies('pop', '365');
}
});
Here is the full code snipet for Rails :
Add the script above to your js repo (in Rails : app/javascript/packs)
In Rails we have a specific packing way for script, so :
Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader = false;
if (typeof define === 'function' && define.amd) {
define(factory);
registeredInModul
...
Add //= require js.cookie to application.js
It will works perfectly for 365 days!
You might be using an API for fetching user from database, so use any unique data like id or email or name to identify user then use localstorage method suggested by #Shaunak D. Just replace key with user's unique field and value with popup state.
Like:
ID : popup_state
Sorry for the mistakes in the reply. I am not on my pc today 😅😛

Meteor Force Rerender of Handlebar Helpers

In Meteor, I have a navigation bar with a custom handlebar method that determines whether or not the tab is active.
JS:
Handlebars.registerHelper('getClass',function(a){
url = document.URL.split("/"); //e.g. http://test.com/something, so 3rd value will have link thing
url = "/" + url[3];
val = Router.path(a);
return url == val ? "active" : "";
});
HTML Snippet:
<li class="{{getClass 'homepage'}}">Home</li>
<li class="{{getClass 'content'}}">Content</li>
<li class="{{getClass 'items'}}">Items</li>
This sets the appropriate active class on a nav-block if I open an entirely new tab, navigating to something like http://localhost:3000/content. However, it won't update the active class if I merely click a new tab. For instance, from the home page to the content page. However, if I click the items tab and then click another tab, it will update, but just once. So if I go to the items tab, items will have the active class and the next class I click will then get it, removing it from items. This only works once, unfortunately. I think it is because items has content from a DB, but I'm not sure. Anyways, I need a way to rerender handlebar helpers, if this is at all possible.
I've tried using the following JS to no avail:
Content = {};
Content._dep = new Deps.Dependency;
Template.header.events({
'click a': function () {
console.log('abc');
Content._dep.changed();
}
})
Does anybody have a way to rerender the handlebars without having to physically reload the page?
Thanks.
I just fixed it. Basically, I added a session with a random number, and updated that on click. It seemed to have done the trick.
Updated code:
Handlebars.registerHelper('getClass',function(a){
url = document.URL.split("/"); //e.g. http://test.com/something, so 3rd value will have link thing
url = "/" + url[3];
val = Router.path(a);
if(Session.get('r'))
void(0);
return url == val ? "active" : "";
});
Template.header.events({
'click a': function () {
Session.set('r', Math.random() + "");
}
})

Radio button list using Javascript with each list choice returning custom text

I am making a custom TinyMCE button for Wordpress, part of the Javascript code looks like this:
(function() {
tinymce.create('tinymce.plugins.Green', {
init : function(ed, url) {
ed.addButton('green', {
title : 'Prompt Text',
image : url+'/images/btn_green.jpg',
onclick : function() {
var prompt_text = prompt("Green Button", "Green Button Text");
var caret = "caret_pos_holder";
var insert = "<div>" + prompt_text + "</div><span id="+caret+"></span>";
if (prompt_text != null && prompt_text != 'undefined')
{
ed.execCommand('mceInsertContent', false, insert);
ed.selection.select(ed.dom.select('span#caret_pos_holder')[0]); //select the span
ed.dom.remove(ed.dom.select('span#caret_pos_holder')[0]); //remove the span
}
}
});
},
createControl : function(n, cm) {
return null;
},
});
tinymce.PluginManager.add('green', tinymce.plugins.Green);
})();
I want to remove the prompt_text function and add a radio button list where a window appears and the user can select one of the options in the list. And each list item should have their unique insert. How is this possible?
For instance, the window should have a list of three options: Tea, Coffee, Water.
If the user selects Coffee, it should insert the text: Coffee wakes you up.
My knowledge of Javascript is very limited which is stopping me from solving this. However, I would presume that this is only possible by creating a jQuery form?
For this you will need to write an own plugin.
You should take a look at the developer tinymce build and have a look at the source code, especially the searchreplace plugin. This plugin uses a tinymce popup and the user is able to select several settings. I suggest you copy that plugin, adjust it to your needs and remove all the stuff you don't need.

Single paged website, which i want to get at a certain point after refreshing page

I have a single paged website, in which i've got a div named sitecontent with the width of 4400, which holds 4 "pages". The pages start at 0px of sitecontent, 1100 px of sitecontent, 2200px of sitecontent, and 3300px.
I use Jquery to set de div position to the right px, so i get the right text displayed. After pressing a link i get for example:
<div id="site-content" style="left: -1100px;">
At one of the pages i have to refresh the page, and after this refresh i want the page to display the same "page" on 1100px, but it starts at 0px, the home page.
Is there any way how i can make sure that the sitecontent starts at -1100px of home?
Thanks in advance,
Cheers
You need to append some identifier onto the hash of the URL that you can parse on the page load.
For example:
http://www.somewebpage.com/somepage#page1
Then in the load of the page, you can inspect this hash value and immediately change the UI to show the new page:
var hash = window.location.hash;
if(hash == "#page1")
$('#site-content').css('left', '-1100px');
You can use a cookie to store the value, then, every time the page loads, you need to check the cookie and deal with the value collected:
The link for Jquery Cookie with download and usage manual!
HTML (example)
<a href="#" title="Go Page 1" id="page_01" class="setCookie">
Click to view page 01
</a>
JQUERY (jquery.cookie)
// SET THE COOKIE
$('.setCookie').bind("click", function() {
var pageNumber = $(this).attr("id");
$.cookie('the_cookie_name', pageNumber, { expires: 7, path: '/' });
});
// READ THE COOKIE
$(function() {
var oldNumber = $.cookie('the_cookie_name');
if (oldNumber !== NULL) {
$("#page_"+oldNumber).trigger("click");
}
});
Note:
The link that you currently use to change pages, should have the class "setCookie" to trigger the cookie creation, and also the id that is being used to identify the page number.
One advantage of this is that you can control for how long is the cookie preserved and thus allowing the visitant to resume the website experience.
An approach very similar to what Tejs is proposing would be to use a hash-based routing framework that listens to hash changes. That will result in much cleaner code since you don't need to define the scrolling in two different places.
Every link in your page is currently being observed by a jQuery event listener (onclick -> moves the content container to the show the desired content). The HTML looks probably somewhat like this: Contact details.
With this approach, you don't need to watch those links. Instead, simply make them change the hash: Contact details.
Now observe the hash and react to changes. I'm using the Simrou framework (https://github.com/buero-fuer-ideen/Simrou) but you can go with any other framework that provides similar functionality.
jQuery(document).ready(function() {
// Define a function that moves the content, e.g. moveContent(3300);
function moveContent(pixelPosition) {
$('#site-content').css('left', '-' + pixelPosition + 'px');
}
// Setup the router
var router = new Simrou({
'page1': function() { moveContent(0); },
'page2': function() { moveContent(1100); },
'page3': function() { moveContent(2200); },
'page4': function() { moveContent(3300); }
});
router.start();
});
That's all the javascript you need!
(and here is a quick and dirty fiddle, demonstrating the whole thing: http://jsfiddle.net/R7F6r/)

Update a jQuery script when user switches to a new tabbed element

I'm having a hard time describing exactly what the problem is.. but the link in question is: http://www.evolutionarycollective.com/events/
You'll notice that when you load the "Calendar" tab, the calendar doesn't show up. If you resize the window, or manipulate the page in some other way, then the calendar appears. The calendar loads fine when it's not within a tab. It's being called in the header with:
<script type='text/javascript'>
jQuery(document).ready(function() {
jQuery('#calendar').fullCalendar({
events: themeforce.events
});
});
</script>
EDIT:
I believe this is the section of the script library that handles the tabs and panes.. (I'm using this with a wordpress theme that calls the tabs via a shortcode)
// jQuery tool's tab creator is not shortcode friendly, transfer the titles to the correct tabs area
jQuery('.bfi_pane').each(function(i) {
var title = jQuery(this).attr('title');
jQuery(jQuery(this).siblings('.bfi_tabs,.bfi_tabs_slide,.bfi_tabs_fade')[0]).append('<div>'+title+'</div>');
});
// Custom slide effect for tabs. slide up then down
jQuery.tools.tabs.addEffect('slide-slide',function(i, done) {
this.getPanes().slideUp(400).eq(i).delay(400).slideDown(400, done);
});
// Custom slide effect for tabs. slide up and down simultaneously
jQuery.tools.tabs.addEffect("slide", function(i, done) {
this.getPanes().slideUp(400).eq(i).slideDown(400, done);
});
// IMPORTANT: SLIDEDOWN JQUERY FIX. we need to assign the correct heights
// so that the slidedown effect doesn't JUMP
jQuery(".bfi_accordion_pane").each(function(i) {
var heightTo = jQuery(this).height();
var paddingTop = parseInt(jQuery(this).css("padding-top").replace('px', ''));
var paddingBottom = parseInt(jQuery(this).css("padding-bottom").replace('px', ''));
var marginTop = parseInt(jQuery(this).css("margin-top").replace('px', ''));
var marginBottom = parseInt(jQuery(this).css("margin-bottom").replace('px', ''));
jQuery(this).css("height", heightTo + paddingTop + paddingBottom + marginTop + marginBottom);
});
// start jQuery tool tabs. we have to do this the long way so we can make
// initialIndex work properly
jQuery(".bfi_tabs_slide").each(function(i) {
var openTab = jQuery(this).attr('rel');
jQuery(this).tabs('> div.bfi_pane', {effect: 'slide-slide', initialIndex: parseInt(openTab, 10)});
});
jQuery(".bfi_tabs_fade").each(function(i) {
var openTab = jQuery(this).attr('rel');
jQuery(this).tabs('> div.bfi_pane', {effect: 'fade', initialIndex: parseInt(openTab, 10)});
});
Is there some way I can somehow refresh the script when that tab lis loaded.. or fire off another document.ready?
Thank you!
The probable explanation is that the full calendar can't figure out its height because when initially created that tab is hidden, which will make it have zero width and height.
Just make the call to .fullCalendar() in a tab switch event handler.
Alternatively use the "off-left" method of hiding tabs, as described in the last few paragraphs of http://jqueryui.com/demos/tabs/

Categories

Resources