For my single page website, I have an index of projects. If a project is clicked it opens up a slideshow on the same page. So basically, I only have one URL, and if anyone wants to link to a specific project, they can't.
I'm trying to make it so that if I click on a project, it changes the URL. And so that URL can be used to get to my website with that project opened.
Here is a link to what I have so far.
For reference, I'm trying to achieve something that is found on this site.
I found some good suggestions here, but what happens when I use something like this (below), a new URL is created but it doesn't open up the project if I renter that URL into the browser.
<a href="#" id='click'>Click to change url to bar.html</a>
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}
You can use `window.onpopstate to sense the back/forward button navigation
window.onpopstate = function(e){
if(e.state){
document.getElementById("content").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};
I would appreciate someone with more skill to check this over for me
You can use id at elements which has slideshow as unique URL; at .ready() start animation of element where id matches .location.hash
$().ready(function() {
// `location.hash`: `id`: `#slideshow1` of element linked to
// from, e.g., `http://example.com/#slideshow1`
var currentSlideshow = $(location.hash);
// do slideshow stuff at `currentSlideshow`: `#slideshow1` element
})
using a hash might work best in this case
$(document).ready(function({
//loading a page
var project = window.location.hash
yourProjectLoadFunction(project);
//setting a url
$('.number').click(function(e){
$this = $(this);
window.location.hash = $this.attr('id');
});
});
Related
I have created a shell like html page which loads other pages into div on link clicks.The issue i am having is to rewrite the url with out a page re-load.
Also checking for hash events to add and rewrite them.
Firstly the links;
<a href = "myexample" onclick="menuPage(this);return false;" >
//result www.mywebsite.com/myexample
function loadPage(){
var tempURL = window.location.hash.substring(1);
$(".nav li").removeClass("active");
$("a[data-role="+tempURL+"]").parent().addClass('active');
if(!tempURL){
$('#pages').animate({opacity: '0.0'},function(){
$("a[data-role='Home']").parent().addClass('active');
$.get('Home/index.html', function(response){
$('#pages').html(response);
scrollOnTop();
$('#pages').animate({opacity: '1.0'});
})
});
}else{
$('#pages').animate({opacity: '0.0'},function(){
jQuery.post(tempURL, function(response){
$('#pages').html(response);
ga('send',{ // google
'hitType': 'pageview',
'title': 'mywebsite',
'location':'http://www.mywebsite.com/'+ tempURL,
'page': '/'+ tempURL
});
document.title = $(response).filter('title').text();
scrollOnTop();
$('#pages').animate({opacity: '1.0'});
tempURL = "";
})
});
}
}
$(window).on("hashchange", function () {
loadPage();
});
function menuPage(obj){
menu = "#" + obj.getAttribute("href");
window.location = menu;
return false;
}
function scrollOnTop(){
jQuery("html, body").scrollTop(0);
}
//The above works 100% expected:**
So lets say i click link or enter the url www.myexample.com/#item1 this will take me to that page all good but lets say i click or type in www.myexample.com/item1 with out hash this will take to the page but all broken as there is a folder named "item1" with an index file in it...
Essentially i would like to add hash into the url:
Once i add to the .htaccess file anything along the lines of : RewriteRule
^([A-Za-z0-9-]+)/?$ # [NC,NE,R=301]
or variations.
This just messes up.
I'm finding it a bit difficult to understand what your code is doing. A jsfiddle or equivalent might help.
It looks like loadPage is only executed when the url hash changes? And an anchor with href of www.myexample.com/item1 doesn't result in a hash change.
My guess is you want to bind a click event to your anchors, so you can intercept the click and run your own custom code (load page snippet without refresh), instead of the browser default behaviour of requesting the url (www.myexample.com/item1) from the server.
Something like:
$('a').click(function() {
/* Your code here. E.g... */
$('#pages').animate({opacity: '0.0'},function(){
$("a[data-role='Home']").parent().addClass('active');
$.get('Home/index.html', function(response){
$('#pages').html(response);
scrollOnTop();
$('#pages').animate({opacity: '1.0'});
})
});
// Returning false prevents browser default behaviour
// Some people don't like it - see http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
return false;
});
I am doing a website where all internal links make the current page fade out and the new contents fade in. I do that with jquery load(). The loading and fading part works fine like this:
var $mainContent = $("#ajaxcontainer"),
$internalLinks = $(".internal"),
URL = '',
$ajaxSpinner = $("#loader"),
$el;
$internalLinks.each(function() {
$(this).attr("href", "#" + this.pathname);
}).on('click', function() {
$el = $(this);
URL = $el.attr("href").substring(1);
URL = URL + " #container";
$mainContent.fadeOut(500, function() {
$ajaxSpinner.fadeIn();
$mainContent.load(URL, function() {
$ajaxSpinner.fadeOut( function() {
$mainContent.fadeIn(1000);
});
});
});
});
As you can see, I am targetting all internal links by a class I've given them (.internal). My problem is that once content gets loaded with ajax, I am not able to target this new content with my jquery, and so the $internalLinks.each() and so on gets broken, meaning that the site just reverts back to the default link behavior.
Another thing which is related to this, is that I want to be able to target this newly loaded content with the jquery.masonry plugin. That also isn't possible the way I'm doing things now.
Thank you very much.
When you update the page, the old .internal links are removed, so the event handler attached to them won't work. Change your code to use event delegation:
$('.internal').each(function() {
$(this).attr("href", "#" + this.pathname);
});
$(document).on('click', '.internal', function() {
$el = $(this);
URL = $el.attr("href").substring(1);
URL = URL + " #container";
$mainContent.fadeOut(500, function() {
$ajaxSpinner.fadeIn();
$mainContent.load(URL, function() {
$ajaxSpinner.fadeOut( function() {
$mainContent.fadeIn(1000);
});
$('.internal').each(function() {
$(this).attr("href", "#" + this.pathname);
});
});
});
});
As you see, I refresh the attribute href of each link after a refresh, too.
** EDITED ** I was missing changing the href attribute the first time. Now it should work!
I've done a lot of reading over the last few years trying to become proficient with JavaScript and it's frameworks. It seems that most texts either teach the rudiments of ajax, loading something into an empty element, or they assume you know what your doing and glance over the data handling portion. I've developed my own methods over time, but having nothing to compare them too. I don't know how efficient they are. When building a ajax based site I typically use jquery and history.js and my code is as follows.
function updateContent(state){
var theUrl = state.data.urlPath; //the url of what needs ajaed in
$('#container #content').fadeOut(500, function(){ //fade out old content
var newContent = {};
newContent.load(theUrl + ' #content', function(){ //load new content into object
newContent.hide(); //hide it so it can be faded in
$('#container').html(newContent); //replace content in container
newContent.fadeIn(500); //fadein content
});
});
}
var History = window.History;
if (History.enabled) {
var State = History.getState();
History.pushState({urlPath: window.location.href}, $("title").text(), State.urlPath);
} else {
return false;
}
History.Adapter.bind(window, 'statechange', function() {
updateContent(History.getState());
});
$(document).on('click', 'a', function(evt){
var testSite = /http:\/\/www.example.com(\/)?/ //regex to test if is local link
var theUrl = $(this).attr('href'); //the url of the clicked link
if(testSite.test(theUrl)){
evt.preventDefault();
History.pushState({urlPath: theUrl}, title, theUrl);
}
});
This is the basics of my code. I feel it is inefficient particularly when the back button is used. When going back the content has to be reloaded. Is there a more efficient way to do this?
I have a link (index.html#services) and a <div id="services> that I'm trying to change the background color of when the link is clicked and then fade back. I'm using the latest jQuery and jQuery Color plugin, and:
$(document).ready(function(){
if(window.location.hash === '#services') {
var service = $('#services');
var originalColor = service.css('background-color');
service.css('background-color', '#FFEE9F').animate({
'background-color': originalColor
}, 3000);
}
});
to do the highlighting, but it's not working. Anyone know why?
That code is only run when the page is loaded, not when a link with a hash is clicked. Try following the link (index.html#services) directly from a new browser tab and it will probably work. What you need to do is run that code when the hash is changed. New browsers have an onhashchange event - but no such thing on older browsers. For old browsers you could poll the hash property every so often to see if it has changed.
If by chance you have a specific identifier (css class, id, name, etc.) on the links that trigger that animation, you could add a click listener to run that code. For example:
function animateBackground() {
var service = $('#services');
var originalColor = service.css('background-color');
service.css('background-color', '#FFEE9F').animate({
'background-color': originalColor
}, 3000);
}
$(function () { // shortcut to $(document.ready)
$('.fade-bg').live('click', animateBackground);
animateBackground();
});
Or use
window.onhashchange = function(){
if(window.location.hash === '#services') {
var service = $('#services');
var originalColor = service.css('background-color');
service.css('background-color', '#FFEE9F').animate({
'background-color': originalColor
}, 3000);
}
};
depending on which browsers you target.
I'm trying to learn jQuery by implementing a simple menu. I've got <div> elements that act as buttons and have links in them. I'm trying to add onclick events to the divs that navigate the browser to the link's address in the div. This is basically my pseudo-code. What would the real code be? How can I improve this? Any feedback appreciated!
// Iterate over each menu button
$('.masterHeaderMenuButton').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var url = $('a', this).attr('href');
this.click(function () {
window.location.href = url;
});
// If the user is on the page for the current button, hilight it
if (window.location.href === url) {
$('a', this).addClass("masterHeaderMenuButtonSelected");
}
});
Try this untested example:
$('.masterHeaderMenuButton a').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var _this = this; // save this ref for click handler.
$( this ).parent().click(function () {
window.location.href = $(_this).attr('href');
});
// If the user is on the page for the current button, highlight it
if (window.location.href === url) {
$(this).addClass("masterHeaderMenuButtonSelected");
}
});
I don't actually use jQuery for such a simplistic task, especially if it involves page redirection. So unless you're looking to do some AJAX-style page loading, stick with standard HTML.
For that task, I use this sweet combo:
$('#nav_links li').live('click', function() {
var ajax_link = $(this).attr('rel');
loadLink(ajax_link);
});
function loadLink(link){
$('#content_window').css('position','relative');
$('#content_window').animate({
'left': '20px',
'opacity': '0'
}, 500, "swing", function() {
$.ajax({
url: '../sections/' + link,
dataType: 'html',
success: function(html) {
$('#content_window').html(html);
}
});
});
}
Awesome, right?
Here's the HTML:
<ul id="nav_links">
<li rel="setting-up.html"><span class="green">|</span>setting up<br></li>
<li rel="features.html"><span class="purple">|</span>features<br></li>
<li rel="more-uses.html"><span class="blue">|</span>more uses<br></li>
<li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li>
</ul>
Have a fun.