Appending hash/subpage to URL when loading content in expanding divs - javascript

I'm loading in separate .html documents inside divs with this code:
JS
$('.thumbnail').click(function() {
var idStr = ("project/"+$(this).attr('id')) + " #projectcontainer";
$('#projectcontainer').animate({opacity:0});
$('#projectcontainer').hide().load(idStr,function(){
$(this).slideDown(500).animate({opacity:1}, function() {
$.scrollTo('#gohere',800);
$('#close').fadeIn(500).css({'display': 'block', 'height': '25px'});
});
});
});
HTML
<div class="thumbnail" id="atmotype.html">
<img src="image.whatever">
</div>
It all works as intended but I also wanna append an ID when you open a project, and also be able to link directly to said content (already expanded in the div). I've been trying around and can't come up with a solution, and that being said I'm pretty awful with JS in general.
Would really appreciate if someone could enlighten me on how this works.

Right now when you click your .thumbnail element, it is firing your click() event and using $(this).attr('id') for the hash/scroll. To make this run when the page load, you should probably break it out to a separate function that takes the ID as a parameter, and then call this function from your click() event as well as a generic page load using a parameter in location.hash.
$(document).ready(function(){
if (location.hash.length>0){
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id){
var idStr = "project/"+ id + "#projectcontainer";
// rest of your code
}
UPDATE:
This is the thing about js it all makes sense when explained but executing it is a bitch. Anyways thanks alot for helping out. Based on your explanation what I get is:
$(document).ready(function() {
if (location.hash.length > 0) {
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id) {
var idStr = "project/" + id + "#projectcontainer";
$('#projectcontainer').animate({
opacity: 0
});
$('#projectcontainer').hide().load(idStr, function() {
$(this).slideDown(500).animate({
opacity: 1
}, function() {
$.scrollTo('#gohere', 800);
$('#close').fadeIn(500).css({
'display': 'block',
'height': '25px'
});
});
});
}
I've tried to fiddle around with the closures and whatever minimal experience i have in bug testing js but i keep getting errors originating from this line:
function addHashAndScroll(id) {

Related

Javascript, passing my string as an argument turns it to a 0

I'm using scrollmagic.io and am making an anchor navigation menu. I'm following this tutorial. The scroll works! Except it was scrolling back to the beginning and not to the page it should be at.
Here is my code:
// init controller
var controller = new ScrollMagic.Controller();
// animate scroll instead of a jump
controller.scrollTo(function(target) {
console.log('scroooooll');
console.log('target = '+target); // THIS IS PRINTING 0
console.log(typeof(target));
/* Commenting out what it should do for simplicity. */
});
// scroll action when you click the nav links
$(document).on('click', 'a[href^=#]', function(e) {
var id = $(this).attr('href'); // get the href of clicked link
if ($(id).length > 0) { // not empty links
e.preventDefault(); // prevent normal link action
// this is the function call
console.log('click');
console.log('id = '+id); // IT PRINTS CORRECT HERE
console.log(typeof(id));
controller.scrollTo(id); // scroll on click
// update the URL
if (window.history && window.history.pushState) {
history.pushState("", document.title, id);
}
}
});
And here is the output of my console log:
click
id = #{the-href-value}
string
scroooooll
target = 0
number
My Javascript is pretty rusty, but this doesn't seem right to me. Why is it changing my variable from a string to a 0 when I pass it as a parameter?
From the documents:
"This function will be used for future scroll position modifications.
This provides a way for you to change the behaviour of scrolling and
adding new behaviour like animation. The function receives the new
scroll position as a parameter and a reference to the container
element using this. It may also optionally receive an optional
additional parameter (see below)"
So, the first parameter is passed by controller.
You will get your parameter after that.
http://scrollmagic.io/docs/ScrollMagic.Controller.html#scrollTo
Try printing console.log(args);
controller.scrollTo(function(scrollPos, targetHrefISent) {
console.log('scroooooll');
console.log('target = '+targetHrefISent); // THIS IS PRINTING 0
console.log(typeof(targetHrefISent));
/* Commenting out what it should do for simplicity. */
});

How can I hide a div that I've just added with a click?

I'm appending some HTML to my button on a click, like this:
jQuery(document).ready(function($) {
$('#sprout-view-grant-access-button').on('click', function(e) {
$(this).toggleClass('request-help-cta-transition', 1000, 'easeOutSine');
var callback = $(e.currentTarget).attr('data-grant-access-callback');
var wrapper = $('.dynamic-container');
console.log(wrapper);
if( typeof window[callback] !== 'function') {
console.log('Callback not exist: %s', callback);
}
var already_exists = wrapper.find('.main-grant-access');
console.log(already_exists);
if( already_exists.length ) {
already_exists.remove();
}
var markup = $(window[callback](e.currentTarget));
wrapper.append(markup);
});
});
function generate_grant_access_container_markup() {
var contact_data_array = contact_data;
var template = jQuery('#template-sprout-grant-access-container')
return mustache(template.html(), {
test: 's'
});
}
As per the code, whatever comes from generate_grant_access_container_markup will be put inside dynamic-container and shown.
My problem is that, the newly added code just doesn't wanna dissapear upon clicking (toggle) of the button once again.
Here's my syntax / mustache template:
<script type="template/mustache" id="template-sprout-grant-access-container">
<p class="main-grant-access">{{{test}}}</p>
</script>
And here's the container:
<div class="button-nice request-help-cta" id="sprout-view-grant-access-button" data-grant-access-callback="generate_grant_access_container_markup">
Grant Devs Access
<div class="dynamic-container"></div>
</div>
I understand that the click event only knows about items that are in the DOM at the moment of the click, but how can I make it aware of everything that gets added after?
I would recommend visibility: hidden. Both display none and removing elements from the dom mess with the flow of the website. You can be sure you would not affect the design with visibility: hidden.
I don't deal with Jquery at all but it seems like this Stack overflow covers the method to set it up well.
Equivalent of jQuery .hide() to set visibility: hidden

jQuery loads external HTML file but does not stay still after page refresh

I am trying to do something different without knowing if it is a good idea or not
I have a navigation menu as the following:
...
<li>Home</li>
<li>FAQ</li>
<li>Contact</li>
...
I do not want to use a server-side scripting because it takes more time to make db connection and define some configuration, and not want to multiply the pages for each one. So I made a master page index.php
in body section
there are two elements:
an h3 element to display the page title and a div to display the content which is called from another html source.
...
<div class="container">
<h3 id="pageTitle"></h3>
<div id="pageContent"></div>
</div>
...
I am using jQuery's click event to load the page into the div
$(function() {
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html"); //removing # char.
});
});
It works fine. But when I press F5 it returns the initial state as normal. How can I load the current page by referencing the address bar (I can see eg. sitename/#mfaq) when page is refreshed.
I think, first I need to detect if page is refreshing and load the corresponding html file in according to the #m**** on the addressbar.
$(function() {
$("a[href^='#m']").click( function(evt) {
// ------ This should work
// renamed parameter elem to evt like corrected in comment
evt.preventDefault();
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});
Add to your DOM ready function:
if (window.location.hash != "") {
$("#pageTitle").text($("a[href='"+window.location.hash+"']").text());
$("#pageContent").load(window.location.hash.slice(1) + ".html");
}
I have made this. It works well. But I am not sure about performance issues:
$(function() {
var address = $(location).attr('href');
var hash = address.lastIndexOf("#");
var page = address.substring(hash+1);
if (hash < 1)
{
$("#pageContent").load("mhome.html");
$("#pageTitle").html("Default Page Title");
}
else
{
$("#pageContent").load(page + ".html");
$("#pageTitle").html($("a[href='" + address.substring(hash) + "']").text());
}
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});

Looping through generated HTML with jQuery

I know if I wanted to bind events to generated HTML, I'd need to use something like .on(), but I've only used it when binding events like .click().
I'm creating a web app that applys a list of colors. Colors are generated from a JSON file. Once fetched, I add it to the page, with certain information contained in attributes. I'd like to do something with the new generated HTML, which is list-elements. But what console.log() is showing me is there is nothing in the parent ul. Even though on the page I see the newly added content.
Here's the entire code based around it.
var setColors = function(){
getColors = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
//console.log(colors);
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
addColors();
}
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
return getColors();
}
$(function(){
setColors();
});
addColors() is where I'm having trouble with. The error says 'Uncaught TypeError: Cannot read property 'firstChild' of null. How can I work with the newly generated HTML?
You are missing parentheses on the children method:
var el = $('#picker').children();
Also, if you want the addColor method to be executed on the newly generated html, then you must add a call to it after the html is generated, from within the getJSON callback method.
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
A few issues:
missing end semi-color
missing parentheses on .children()
children() returns a jQuery object, no need for $(el)
Updated:
window.addColors = function(){
var $el = $('#picker').children();
$el.each(function(){
// do stuff here, but could attach each() to above, after children()
});
};

How do I show or hide div, based on position of another div

I have the following jquery that slides a div horizontally:
$('.nextcol').click(function() {
$('.innerslide').animate({'left': '-=711px'}, 1000);
});
$('.prevcol').click(function() {
$('.innerslide').animate({'left': '+=711px'}, 1000);
});
What I want to happen is this... if the div.innerslide has a position that is left: 0px then I want to hide div.backarrow. If the position is not left: 0px, then it shows it.
Any help would be greatly appreciated.
EDIT (added HTML Markup)
<div class="backarrow prevcol">
<div id="mainleft" class="overflowhidden">
<div class="innerslide">
<div class="col">my content including next</div>
<div class="col">my content including next</div>
<div class="col">my content including next</div>
</div>
</div>
Try this:
if ($('.innerslide').css("left") == 0) {
$('div.backarrow').hide();
} else {
$('div.backarrow').show();
}
Fix for Double-Click Issue:
From what you described in your comment about the issue when the visitor double-clicks, it sounds like the double-click is causing two of the animation events to fire. To keep this from happening, you can either disable the click handler while the animation is running and re-enable it once it is finished, or you can try to write a new thread to continually check the element's position. One of these solutions is not a good idea - I'll let you figure out which one :) - but the other actually has a very simple solution that requires little change to your existing code (and may actually reduce your overhead by a teeny weeny amount):
$('.nextcol').on("click.next", function() {
$('.innerslide').animate({'left': '-=711px'}, 1000, showHideBack());
$(this).off("click.next");
});
$('.prevcol').on("click.prev", function() {
$('.innerslide').animate({'left': '+=711px'}, 1000, showHideForward());
$(this).off("click.prev");
});
Then add this this line to showHideBack() (and a complementary one to showHideForward() if you are using that):
$('.nextcol').on("click.next".....
I suggest that you write a function to set each click handler and another to remove each one. This will make your live very easy and the whole solution should reduce overhead by removing unnecessary click handlers while the animation is running.
Note: the animation method often calls its callback before the animation finishes. As such, you may wish to use a delay before calling the showHide... method(s).
Let me know if you have any questions. Good luck! :)
UPDATE:
Here is the updated version of the fiddle you gave me with all bugs ironed out. It looks like I misunderstood part of your goal in my original solution, but I straightened it out here. I have also included the updated jQuery, here:
var speed = 1000;
var back = $("div.backarrow");
var next = $(".nextcol");
var prev = $(".prevcol");
var inner = $(".innerslide");
function clickNext(index) {
next.off("click.next");
inner.animate({
'left': '-=711px'
}, speed, function() {
back.show(); //this line will only be hit if there is a previous column to show
next.delay(speed).on("click.next", function() {
clickNext();
});
});
}
function clickPrev() {
prev.off("click.prev");
inner.animate({
'left': '+=711px'
}, speed, function() {
if (inner.css("left") == "0px") {
back.delay(speed).hide();
prev.delay(speed).on("click.prev", function() {
clickPrev();
});
} else {
back.delay(speed).show();
prev.delay(speed).on("click.prev", function() {
clickPrev();
});
}
});
}
next.on("click.next", function() {
clickNext();
});
prev.on("click.prev", function() {
clickPrev();
});​
I was going to also include a condition to check if you were viewing the last column, but, as I don't know what your final implementation will be, I didn't know if it would be applicable. As always, let me know if you need help or clarification on any of this. :)
You could try the step option — a callback function that is fired at each step of the animation:
$('.prevcol').click(function() {
$('.innerslide').animate({ left: '+=711px' },
{
duration: 1000,
step: function(now, fx) {
if (now === 0 ) {
$('div.backarrow').hide();
} else {
$('div.backarrow').show();
}
}
});
});
More examples of usage in this article The jQuery animate() step callback function

Categories