Hashtag to trigger a jQuery animation - javascript

I have received help earlier in another question about some jQuery transitioning and I got my website to behave properly, but now I need to get a bit deeper into this jQuery transitioning...
I need a particular effect/transition to happen based on the hashtag that is written in the address bar. This is the code provided by the other question by pckill:
$('.nav').on('click', 'li', function(){
var id = $(this).data('id');
var breadcrumbs = document.getElementById('breadcrumbs');
breadcrumbs.innerHTML = 'IMGit » <span class="capitalize">' + id + '</span>';
var current = $('#inner').find('[data-page=' + id + ']');
if (current.hasClass('hidden'))
{
current.css('marginLeft', '-200%');
$('#inner > div').not(current).animate(
{marginLeft: '100%'},
'fast',
function(){
$('#inner > div').not(current).addClass('hidden');
current.removeClass('hidden');
current.animate({marginLeft: '0%'}, 'fast');
});
}
});
And this is the HTML: http://pastebin.com/pu7jmefC
Let's say, for example, I link someone to http://mywebsite.com/index.php#remote, I want the user to be transitioned with jQuery to the proper div. The approach above works perfectly with the menu I have, but I want to be able to share the URL with someone and they'd still be able to get directly to the proper div.
I think the code above needs some altering to make it do what I seek, but I unfortunately, I'm not that good in Javascript/jQuery.
I guess we'd have to touch the code somewhere around here: $('#inner > div').not(current).
I know we have window.location.hash to work with hashtags, but I have no idea how to put it to use in the code above.
Ideas?

If you just need to check the hash on page load and perform an action accordingly, that's really simple. First of all you need to move the logic of transitioning to a div into a separate function, say transitionToDiv:
function transitionToDiv(id) {
var current = $('#inner').find('[data-page=' + id + ']');
if (current.hasClass('hidden'))
{
current.css('marginLeft', '-200%');
$('#inner > div').not(current).animate(
{marginLeft: '100%'},
'fast',
function(){
$('#inner > div').not(current).addClass('hidden');
current.removeClass('hidden');
current.animate({marginLeft: '0%'}, 'fast');
});
}
}
And change the click event (the code in your question) to:
$('.nav').on('click', 'li', function() {
var id = $(this).data('id');
var breadcrumbs = document.getElementById('breadcrumbs');
breadcrumbs.innerHTML = 'IMGit » <span class="capitalize">' + id + '</span>';
transitionToDiv(id);
}
Now, to transition to a div on page load based on the address hash, simply add these lines at some point after page load:
var id = window.location.hash.substr(1);
transitionToDiv(id);

Related

Transfer data from one page to another jQuery Mobile

I using PhoneGap to create a Geolocation App following this excellent tutorial (link). Unfortunatelly, I'm having an issue that I can't figure out. The relevant parts that are giving me a headache are these:
//Section 1
$('#history').on('pageshow', function () {
tracks_recorded = window.localStorage.length;
$("#tracks_recorded").html("<strong>" + tracks_recorded + "</strong> workout(s) recorded");
$("#history_tracklist").empty();
for (i = 0; i < tracks_recorded; i++) {
$("#history_tracklist").append("<li><a href='#track_info' data-ajax='false'>" + window.localStorage.key(i) + "</a></li>");
}
$("#history_tracklist").listview('refresh');
});
//Section 2
$("#history_tracklist li a").on('click', function () {
$("#track_info").attr("track_id", $(this).text());
});
//Section 3
$('#track_info').on('pageshow', function () {
var key = $(this).attr("track_id");
$("#track_info div[data-role=header] h1").text(key);
var data = window.localStorage.getItem(key);
data = JSON.parse(data);
});
Section 1 works just fine, the data is stored, and the list is created without any issues. But then in Section 2 is when everything goes to hell. By clicking on the element, a new attribute (track_id) is supposed to be created, but it doesn't. Therefore, in Section 3, the "var key" won't get a value, and as a consequence, "var data" will be null also. As you can imagine, nothing works from there. What am I doing wrong here? I only included what I considered the relevant code, but if more is needed I'll do so. Thansk!
In section 2, I think you just need to delegate click handling to the "#history_tracklist" container, as follows :
$("#history_tracklist").on('click', "li a", function () {
$("#track_info").attr("track_id", $(this).text());
});
Without delegation you have a rule saying :
when any existing li a element within #history_tracklist is clicked execute my function
With delegation, you have a rule saying :
when any existing or future li a element within #history_tracklist is clicked execute my function

How to keep the selected menu active using jquery, when the user comes back to page?

I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});

jQuery slide changing with index and fadeout -- jumpiness

I am working on a jQuery slideshow plugin. One of my methods involves switching back and forth between pictures. I have been pretty successful in creating it, here is an isolated case with the code thus far for the particular method:
var images = $("#simpleslides").children("img");
$(".slideButtons ul li").on("click", "a", function() {
var anchorIndex = $(this).parent().index();
var $activeSlide = $("#simpleslides img:visible");
var $targetSlide = $(images[anchorIndex]);
if($activeSlide.attr("src") == $targetSlide.attr("src") || $targetSlide.is(":animated")) {
return false;
} else {
$activeSlide.css({ "z-index" : 0 });
$targetSlide.css({ "z-index" : 1 });
$targetSlide.stop().fadeIn("slow", function() {
$activeSlide.hide();
});
}
});
Here is a fiddle to see it in working action: http://jsfiddle.net/ase3E/
For the most part, this works as you would expect it to. When a user clicks on the corresponding number, it fades in the picture.
However, I am running into some jumpiness and occasionally a complete hide of the slides when I am clicking around quickly. If you play with the fiddle, you will see what I am referring to Try clicking around on each image to see.
I have adopted stop which I thought would fix the problem but has not. I have put the hide method after the fadeIn callback, but that has also not helped the situation.
What am I doing wrong here??
LIVE DEMO :)
var images = $("#simpleslides").find("img");
$(".slideButtons ul").on("click", "li", function(e) {
e.preventDefault();
var i = $(this).index();
images.eq(i).stop().fadeTo(500,1).siblings('img').fadeTo(500,0);
});

JScrollPane Plugin - Reinitialize on Collapse

I'm trying to get JScrollPane to reinitialize on expand/collapse of my accordion found here. You can demo the accordion by clicking on one of the parents (Stone Tiles, Stone Sinks, Stone Wall Clading, etc).
Right now I set it as a click event using the following JQuery...
var pane = $('.menuwrap')
pane.jScrollPane();
var api = pane.data('jsp');
var i = 1;
$("ul#widget-collapscat-5-top > li.collapsing").click(function() {
$(this).delay(3000);
api.reinitialise();
});
It seems to work when you click the parent the second time, but not the first. I have no idea why but I went into trying to edit the JS for the accordion so that I can add this function when the collapse is complete (as opposed to trying to do this click workaround). The collapse JS can be viewed here.
I tried to add the JS for the reinitialize function here, but I think I'm not doing something properly.
May you point me in the right direction?
Thanks!
The api.reinitialise() is working properly. What is happening is that it updates the size when you click, and at this moment the element is not expanded yet. You may notice that if you expand, colapse and expand again the same section, nothing happens. But if you expand one and then click another one, the ScrollPane will adjust to the size of the first expanded element.
You can solve this with events: place $(this).trigger('colapseComplete') when the colapse ends. Then you can use:
//Listening to the colapseComplete event we triggered above
$("#widget-collapscat-5-top > li.collapsing").on('colapseComplete', function() {
api.reinitialise();
});
Maybe you can alter the addExpandCollapse function to call the reinitialise function at the end of each of its click actions this way :
function addExpandCollapse(id, expandSym, collapseSym, accordion) {
jQuery('#' + id + ' .expand').live('click', function() {
if (accordion==1) {
var theDiv = jQuery(this).parent().parent().find('span.collapse').parent().find('div');
jQuery(theDiv).hide('normal');
jQuery(this).parent().parent().find('span.collapse').removeClass('collapse').addClass('expand');
createCookie(theDiv.attr('id'), 0, 7);
}
jQuery('#' + id + ' .expand .sym').html(expandSym);
expandCat(this, expandSym, collapseSym);
api.reinitialise(); // HERE
return false;
});
jQuery('#' + id + ' .collapse').live('click', function() {
collapseCat(this, expandSym, collapseSym);
api.reinitialise(); // and HERE
return false;
});
}
and to be on a safer side, make sure you have the var api = pane.data('jsp'); line before the above piece of code anywhere in the file.

JQuery: How do you change a graphic on a mouse hover event?

Using JQuery, how do I change a map icon whenever I mouse hover over a row in an HTML table/div?
Here is an example:
http://www.sfsunriseidx.com/homes/94131/?uuid=9ed7269b-5327-4c88-ba15-f700ed343d69&source=REDIR
Notice when you mouse hover over a home listing on the left, the corresponding map icon on the right changes.
Question: how do I emulate this functionality using JQuery?
Update: It was suggested below that an ID linked the two elements. If that is the case, how would you still accomplish this?
Use the for="" attribute in html, like
Hover Link
On the image:
<img id="mapIcon4" src="myImg.png" />
jQuery, using the hover function to animate the corresponding ID, the same one in the for:
$(".mapHover").hover(function() {
$("#" + $(this).attr('for')).animate({"left": "-=50px"}, "slow");
}, function() {
$("#" + $(this).attr('for')).animate({"right": "+=50px"}, "slow");
});
Probably both elements are linked by a ID..
Something like this:
$(document).ready(function() {
var googleMap = $("#googleMaps");
$('a', '#mapLinks').hover(function() {
var index = $(this).index(this);
$('img:eq(' + index + ')', googleMap).animate({
width: '+=10%'
});
}, function() {
var index = $(this).index(this);
$('img:eq(' + index + ')', googleMap).animate({
width: '-=10%'
});
});
});
Just make sure you change the "#googleMaps" and "#mapLinks" thing :)

Categories

Resources