History.pushState URL + Scroll To Effect - javascript

I'm changing my sites URLs to /name using History.pushState, which is working but the page does not scroll to the location of the site it is suppose to.
index.php:
<nav>
<ul>
<li>Work</li>
<li>About</li>
<li>Services</li>
<li>Blog <!-- Coming Soon... --> </li>
<li>Contact</li>
</ul>
</nav>
<article class="content" id="work">
...
<article class="content" id="about">
...
jquery.page.js:
_saveState = function( chapter ) {
if (History.getState().url.queryStringToJSON().chapter !== chapter) {
var page;
if (chapter == 1)
page = "/work";
if (chapter == 2)
page = "/about";
if (chapter == 3)
page = "/services";
if (chapter == 4)
page = "/blog";
if (chapter == 5)
page = "/contact";
else
page = '?chapter=' + chapter;
History.pushState(null, null, page)
}
},
...
_goto = function( chapter ) {
var chapter = chapter || History.getState().url.queryStringToJSON().chapter,
isHome = ( chapter === undefined ),
$article = $( chapter ? '#' + 'chapter' + chapter : '#' + 'introduction' );
...
When the user clicks on a link in the navigation menu, how do I make the page jump to the location it is suppose to, as seen in the tutorial I've been following?

their is no problem in your javascript its prefect but the problem was in your html please correct the content-wrapper div it was not enclosing the articles it was like
<div class="content-wrapper"></div><article></article>...
it should be
<div class="content-wrapper"><article></article>....</div>

History.getState().url.queryStringToJSON().chapter is trying to find a query parameter chapter in your URL, which doesn’t exist anymore since you changed the URL format.
Without having worked with $.History, it seems to me that you could try to compare against the URL, using something along the lines of:
if (History.getState().hash.replace(/^\/|\/$/g, '') !== chapter) { ... }
// replace(/^\/|\/$/g, '') will remove a leading and/or trailing slash '/'
Note though, that if your site does not live on the root (e.g. http://example.com/foo/bar/portfolio) you’ll still have to deal with the rest of the URL, since History.getState().hash will return you /foo/bar/portfolio instead of /portfolio.
(On a side note: If you find yourself writing repeatedly else if, try using a switch instead.)

Related

JavaScript, create anchor with array, doesn't work [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I tried using jsfiddle, it works properly there, but for whatever reason, the file didn't work when i run it on chrome. i also have other code concurrently (specifically form validation) but they are working fine, and there are no clashing var and function too. I know that i should just use other simpler way but unfortunate this is part of the requirement to use array in the dropdown
function makeAnchor() {
var div = document.createElement('div');
var options = ['ENCLOSED SPACE SANITISATION', 'EVENT HYGIENE MANAGEMENT', 'WIDE AREA SANITISATION', 'OBJECT DISINFECTION'];
for (var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var ok = options[i]
a.href = "./service" + (i + 1) + ".html"
a.appendChild(document.createTextNode(ok));
div.appendChild(a);
}
return div;
}
document.getElementById('dropsc').appendChild(makeAnchor());
<!-- Nav Bar -->
<nav class="sticky-top">
<ul>
<li class="dropdown font-josefin">
<a class="dropbtn">SERVICES</a>
<div id="dropsc" class="dropdown-content">
<!-- ENCLOSED SPACE SANITISATION
EVENT HYGIENE MANAGEMENT
WIDE AREA SANITISATION
OBJECT DISINFECTION -->
</div>
</li>
<li class="font-josefin">ABOUT ME</li>
<li class="font-josefin">ENQUIRY</li>
<li class="font-josefin">ENHANCEMENTS</li>
<li class="font-josefin">DISCLAIMER</li>
</ul>
</nav>
document.getElementById('dropsc').appendChild(makeAnchor().cloneNode(true));
Try this

HTML if div content is long show button

I have this django app I made, and it is a blog app. The blogs are quite long, so I want to be able to show a little and then more of the div's text if the blog is long. Here is my html:
<a style="text-decoration: none;color: #000;" href="{% url 'post-detail' post.id %}">
<div id="content-blog"><p class="article-content">{{ post.content|safe }}</p></div>
</a>
I want something like this:
<script>
content = document.getElementById("content-blog");
max_length = 1000 //characters
if(content > max_length){
//Do something
}
</script>
So how would I get this to actually work. To summarize, I want this to check if a div is longer than 1000 characters, and if it is, to run the if statement above. Thanks.
You need to use innerText, please change your JS code to
<script>
var content=document.getElementById("content-blog").innerText.length;
max_length = 1000 //characters
if(content > max_length){
//Do something
}
</script>
To get all the blogs and do something to them all:
let blogs = Array.prototype.slice.call(document.getElementsByClassName("article-content"));
blogs.forEach(blog =>
if (blog.innerText.length > 1000) {
// Do stuff with the blog
} else {}
)
You could also modify the context in your view, or add a model property to your blog mode, to make a preview_text for the blog post. Like post.content[:100] for first 100 characters of post.

variable is not defined when i try to get an id

this is my code: (Im using a CMS based in MVC).
html:
<div class="item_group_title">
<a id="title_{$group.title}" data-tip="{lang("show", "store")}" class="hide_group" href="javascript:void(0)" onClick="Store.toggleGroup(this)">
<img src="{$url}application/images/icons/{$group.title}.png">
</a>
</div>
...
<section class="item_group" id="group_{$group.title}" {if $minimize}style="display:none"{/if}>
</section>
js:
toggleGroup: function(field)
{
var titleId = $(field).attr('id');
var groupId = $titleId.text().replace('title_', 'group_');
var group = $($groupId);
if(group.is(":visible"))
{
$(field).attr('data-tip', lang("hide", "store"));
}
else
{
$(field).attr('data-tip', lang("show", "store"));
}
group.css("display","visible");
},
What im trying to get is: When i click on the link the section below should be visible. There will be some links and some sections and each link will be affect one section.
My problem is that i receive this error: $titleId is not defined
Any ideas? Thank you so much
titleId and $titleId is not the same thing, the dollarsign is just another character that is part of the variable name.
How about
var $titleId = $(field).attr('id');
var $groupId = $titleId.text().replace('title_', 'group_');
var group = $($groupId);
It's the same with a lot of your variables, make sure they either have the dollarsign, or they don't.

Javascript: Schema Explorer Chrome Extension loop needs to ignore irrelevant nested elements

This should be easy for a Javascript expert.
For those who don't know what schema is ( http://schema.org ), it's a new way for Search Engines to read content on a webpage. It works by tagging relevant data with specific tags.
For those who do know what it is, here is a chrome extension (Schema Explorer) that makes it easy to inspect what your data looks like on your page. See the example.
NOW: There is a tiny issue with the extension where by is does not skip/ignore empty nested elements. Here are two examples: The first works perfectly but, the second bombs because of the empty <div> tag:
First example works:
<div itemscope="" itemtype="http://schema.org/Movie">
<h1 itemprop="name">Avatar</h1>
<div itemprop="director" itemscope="" itemtype="http://schema.org/Person">
Director: <span itemprop="name">James Cameron</span> (born <span itemprop="birthDate">August 16, 1954</span>)
</div>
<span itemprop="genre">Science fiction</span>
Trailer
</div>
Seconds example gives issues:
<div itemscope="" itemtype="http://schema.org/Movie">
<div>
<h1 itemprop="name">Avatar</h1>
<div itemprop="director" itemscope="" itemtype="http://schema.org/Person">
Director: <span itemprop="name">James Cameron</span> (born <span itemprop="birthDate">August 16, 1954</span>)
</div>
<span itemprop="genre">Science fiction</span>
Trailer
</div>
</div>
I had a look at the extension and it's actually very well put together with one javascript file doing most of the work. Here is the code that does the looping, however it needs to be able to skip empty nested elements and perhaps be a little bit more robust in general:
var __explore = function(node, parentData)
{
if (parentData === null || parentData === undefined)
{
parentData = __dataTree;
}
if (node.getAttribute)
{
var isItemScope = node.getAttribute('itemscope');
var hasItemProp = node.getAttribute('itemprop');
var itemtype = node.getAttribute('itemtype');
var childs = node.childNodes;
var i = 0;
var tmp = new Array();
while (i < childs.length)
{
if (isItemScope !== null)
__explore(childs[i], tmp);
else
__explore(childs[i], null);
++i;
}
if (isItemScope !== null)
{
parentData.push({name : 'scope', value : hasItemProp, type : itemtype, childs : [tmp], node : node});
}
else if (hasItemProp && parentData)
{
parentData.push({name : hasItemProp, value : node.innerText});
}
}
}
Here is the complete versions of the contentscript.js https://gist.github.com/3413475
Hopefully someone can help me with this. For the record I've contacted the author but he's been preoccupied with more urgent matters.
I made it work as expected: http://jsfiddle.net/vyrvp/1/ but I must confess that this is a bit hackish. This code may need some more refactoring to make it work for all cases and make it readable.

Inserting Anchors in a Javascript Photo Gallery - Not Working?

I am using jAlbum(with the lightflow skin) to create a photo gallery for my website. The gallery loads and is in a nice carousel format. I would like to add anchors that way I can link directly to a certain photo within the gallery. I tried to add an anchor in the HTML yet it does not work. I assume this is because when the page loads the gallery takes a few seconds to load and thus does not redirect to the anchor. I easily could be wrong and need some advice on what I should try to get anchors to work. Here is an example code for the anchor and the photo itself:
<div class="item">
<a name="anchor3" id="anchor3"></a>
<img class="content hidden" src="thumbs/tree-w-sun.jpg" alt="Gifts" />
<div class="ref hidden">item8</div>
<div class="caption"><h3>Gifts</h3></div>
<div class="comment hidden"></div>
<div class="author hidden"></div>
<div class="params hidden"></div>
<div class="info hidden"><div><p>Artist: UBhapE2</p></div></div>
<div class="thumbWidth hidden">261</div>
<div class="thumbHeight hidden">350</div>
<a id="item8" class="lightwindow hidden" title="<h3>Gifts</h3>"
rel="gal[cat]" href="slides/tree-w-sun.jpg" ></a>
</div>
I have tried linking to the anchor I inserted (anchor3) and to the id inserted by jAlbum (item8) and neither work.
There are a few scripts that control the gallery and will put them here:
Script 1 - "Lightflow JS"
var LightFlowGlobal = {};
function getParam( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Script 2 - "ContentFlow JS" This JS is long and for sake of space I put the link directly to the JS file here
Script 3 - This script is in the page:
<script language="JavaScript" type="text/javascript">
var startItem = getParam('p');
if(startItem == "") startItem = "first";
if(startItem.isNaN) startItem = "'"+startItem+"'";
new ContentFlow('contentFlow', {
reflectionColor: "#000000",
maxItemHeight: 350,
marginTop: 50,
reflectionHeight: 0.25,
endOpacity: 1,
startItem: startItem,
circularFlow: false,
stretchThumbs: false
});
function lightWindowInit() {
LightFlowGlobal.myLightWindow = new lightwindow({
infoTabName : "More Info",
rootPath: "res/lightwindow/",
loadingTxt: "loading or ",
cancelTxt: "cancel",
playTxt: "start slideshow",
stopTxt: "stop slideshow",
slowerTxt: "slower by 1 second",
fasterTxt: "faster by 1 second",
downloadSlideTxt: "Download",
downloadSlide: false,
showSlideshow: false,
slideshowDuration: 5000,
circular: false,
animationDuration: 0.25
});
}
LightFlowGlobal.readyJS=true;
var rootPath = ".";
</script>
I am unsure what other scripts or css is needed. I link to the test-gallery I am working with here if you need to view the page. I will post additional info if requested.
So now how do I get anchors to work with this? I am not that great at javascript so please explain the answer vs "you need to add this function to the script" without explaining.
Thank Your for any and all assistance!
On the ContentFlow site, under Documentation --> items as links, the developer specifically states that "no element within the item may contain any anchors". maybe someone can offer a way around this restriction.
I figured out a way answer was provided by the Photo Gallery Creater:
It's not only the js. You'd need to pass a parameter to AddThis in order to
identify the image. Without it, you wouldn't know which image has been clicked.
The best would be to use LightFlow's query paramter p=index, where index is the
number of the image of the current web page.
For example, the following link would focus the 4th image of the gallery
(index begins at 0): http://your-domain.com/album/index.html?p=3

Categories