JQuery hide div based on url hash and string - javascript

I'm attempting to hide a div based on the url hash tag. I'm using a jquery plugin called zozo tabs that allows for deep-linking and it shows and hides divs.
There is a particular div on the page (not in the tab area) I would like to hide given the url/s. I've searched but cannot figure it out. Please excuse my javascript noobness!!! I've tried this. No such luck. It doesnt seem to work. Any help would greatly appreciated.
I've tried php but it doesnt work on the hash
To start the plugin creates this type of url
http://localhost:8888/site/funds/#tabbed-nav=fund-strategy
The html is:
<ul>
<li data-link="fund-strategy"><a>Fund Strategy</a></li>
<li data-link="portfolio-characteristics"><a>Portfolio Characteristics</a></li>
<li data-link="performance"><a>Performance</a></li>
</ul>
<div class="strategy">This copy shows when the li is clicked on</div>
This is me attempting to hide a div given the url with js
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var url = document.location.href;
if (url.indexOf('http://localhost:8888/site/funds/#tabbed-nav=fund-strategy') >= 0) {
jQ('.fourth').hide();
};
});
<div class="fourth">Hide me please!</div>

Just try to use something like this:
var currentHash = window.location.hash;
if (currentHash=="#tabbed-nav=fund-strategy") {
$('.fourth').hide();
}
Be sure that there is a html element with class 'fourth' in your html code. Otherwise this will not hide anything.

I think i pinpointed the problem. The zozo tabs utilizes hashchange. So after hitting my head against the wall and HUGE inspiration from users here. I downloaded the ba.hashchange and wrapped the given answers in a hashchange function here is the code if anyone is interested. This seemed to work.
var jz = jQuery.noConflict();
jz(function(){
jz(window).hashchange( function(){
// Alerts every time the hash changes!
var hash = document.location.hash;
if (hash == '#tabbed-nav=risk' || hash == '#tabbed-nav=fund-strategy') {
jz('.fourths').show();
} else {
jz('.fourths').hide();
}
})
jz(window).hashchange();
});

Related

jQuery Hide/Show DIV on change of anchor text

I have one page website which changes URL #id or anchor text on scrolling and on navigation click. I have an image positioned fixed at the center of the site. The site is divided in different sections and the image shows in all the sections. I do not want to show the image on the first section as it is unrelated to the content of the 1st section but will be showed in all next sections. How can I make it work?
What I have tried till now but not working:
$(document).ready(function(){
$(".phone").hide();
var idSample = window.location.href.split("#");
var id = "#"+idSample[1];
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});
Rest in Fiddle: https://jsfiddle.net/shubhamjha1000/vh7bu32q/
I don't want that phone to be seen on 1st section but on rest of the sections. Please help me guys!
You can use the answer written in this question to listen to changes in the window see what url you are on and show or hide the phone accordingly....
Example:
$(function(){
// Bind the event.
$(window).hashchange(hashchanged);
// Trigger the event (useful on page load).
hashchanged();
});
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
if(hash == "#first") {
// Hide element
} else {
// Show element
}
}
But still even though what you are planning to do will work with that solution I think it would still look bad on the app it self and instead of a hovering phone maybe you can create the phone as an img inside the relevant containers and hide and show with id...
You can simply use a substring on your location.hash for get your hash tag
$(document).ready(function(){
$(".phone").hide();
var id = window.location.hash.substr(1);
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});

jquery-ui tabs getting anchor href with older jquery 1.8

I have had a look around and sorry if I have missed the answer. Came across this post. And a few others circulating now on SO and wondered if there was an easier way:
The problem:
<ul>
<li><a id="test1" href="/someurl">click1</a></li>
<li>click1</li>
<li>click1</li>
</ul>
Followed by
<ul id="ui-tabs-1" ></ul>
<ul id="ui-tabs-2" ></ul>
Everything is working what I am trying to do is alter the url in any given selected li from href="/someurl" to href="/someurl?params=something"
var href = $('#test1').attr('href')
console.log('link is '+href)
//this returns correct link
$('#tabs').on('refreshListing',function(event,target) {
$(this).tabs('load',$(this).tabs('option','selected'));
var href = $('#test1').attr('href')
console.log('link is '+href)
//this returns #ui-tabs-1
});
At the moment the above function simply reloads the url, when attempting to get url of li I get #ui-tabs-1 not /someurl
There are some weird stuff going on above in the refreshListing the value of actual ID link in a href is converted and ultimately before it does the load on that tab id I wish for it access new url rather than well at the moment it is hard to tell what on earth is driving all this oddness
Never mind solved it, the issue was a little more complex than described.
You have tabs that are dynamic but also have a search form in above
$('#tabSpecific').on('refreshListing',function(event,target) {
//This was previously
//var obj = $('#search')
//Now changed to - this to fix underlying (above issue)
var obj = $('#search').find("input").not("input[type='hidden']").filter(function() {
return this.value;
});
if (obj.length > 1) {
obj.trigger('submit');
} else {
$(this).tabs('load',$(this).tabs('option','selected'));
}
})
The problem had been it was always returning a size greater than 1 (due to other complications of multi tabs sharing same common things) so it hit the submit feature which submitted - page through search form of tab - this then didn't reload actual tab when required....
Anyhow it is hard to express it all but the above fixes behaviour to how I need it to work - only when it actually has search it will submit otherwise it will reload which should work correct for my situation

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>

jquery load image to div after clicking href

I know this has been asked many times here, actually I found plenty of questions, each of them with a very good answer, I also followed those answers, used the different ways I found but I still don't get it to work.
What I'm trying to do is to load an image into a div, after clicking a link, instead of redirecting to a new page.
I'm using Pure Css (http://purecss.io/) to create a menu, the menu is made of a list, and each list item has a link inside it, like so:
<div class="pure-menu pure-menu-open" id="vertical-menu">
<a class="pure-menu-heading">Models</a>
<ul id="std-menu-items">
<li class="pure-menu-heading cat">Menu heading</li>
<li>Model 1</li>
</ul>
</div>
In that same html file, I have another div where I want to load the image:
<div id="model-map"></div>
I've tried the following ways, using jquery, in a separate js file:
I followed the selected answer for this question, which seemed to have the best approach (Can I get the image and load via ajax into div)
$(document).ready(function(){
console.log("ready"); //this shows on console
$('.model-selection').click(function () {
console.log("clicked"); //this doesn't show after clicking
var url = $(this).attr('href'),
image = new Image();
image.src = url;
image.onload = function () {
$('#model-map').empty().append(image);
};
image.onerror = function () {
$('#model-map').empty().html('That image is not available.');
}
$('#model-map').empty().html('Loading...');
return false;
});
});
As you see, the console.log("clicked") never executes, I'll be ashamed if it's something stupid, cause it seems that the function is not handling the click event properly.
I get the image of course, but in a new page (default behavior of clicking the href) and I want it to load on the div without being redirected. I hope you can help me.
Thanks in advance!
Edit
The code above is working, and both answers are correct, the issue was due to some code inside tags in my html ( YUI code to create the dropdowns for the menu) and it was conflicting with my js file. I moved it to the actual js file and now it works as expected.
Thanks!
You need to use event.stopPropagation();
$('.model-selection').click(function( event ) {
event.stopPropagation();
// add your code here
});
You just need to prevent the default behavior of moving to a new page for <a> tags, to do this say e.preventDefault() first:
...
$('.model-selection').click(function (e) {
e.preventDefault(); // Stops the redirect
console.log("clicked"); // Now this works
...
)};
...

change url to reflect content on the page hidden / displayed with Javascript

I am currently making a website for an architecture firm, HLArchitects. In the projects page I have created an HTML / Javascript image gallery. slightly above the main big image to the right an option can be found to choose between images / information. I use Jquery to show and hide the information or the images, however i don't feel this is such a great way to do so. It can be viewed here for reference: http://www.hla.co.za/projects/Hyuandai_Training_Centre/
Here is the relevant Javascript:
$(".selector a").click(function(){
if ($(this).attr("data-show") == "images") {
$("#info").fadeOut("fast");
$("#displayImg").fadeIn("fast");
$("#imageFlow").fadeIn("fast");
} else if ($(this).attr("data-show") == "info") {
$("#displayImg").fadeOut("fast");
$("#imageFlow").fadeOut("fast");
$("#info").fadeIn("fast");
}
})
Relevant HTML:
<p class="selector">images | information</p>
My problem is that the url does not change to reflect the content, but I do not want to make a separate page. I could imagine i would need to make use of link anchor's but am not to sure how to do so.
Thank you in advance
You can change the hash of an url by using:
window.location.hash = 'images';
EDIT:
Firstly, in this context you don't need to include the hash symbol!
Secondly, I missed the obvious, you only need to change the HTML to this to update the URL correctly:
<p class="selector">
images
information
</p>
Then you can use the following in your jQuery, note I've included the attribute check inside the selector itself:
$(".selector a[href=#images]").click(function() {
$("#info").fadeOut("fast");
$("#displayImg").fadeIn("fast");
$("#imageFlow").fadeIn("fast");
});
$(".selector a[href=#info]").click(function() {
$("#displayImg").fadeOut("fast");
$("#imageFlow").fadeOut("fast");
$("#info").fadeIn("fast");
});
If you want to refresh the page and get the same content, you can check the hash tag by doing the following (you may need to edit this depending what elements are showing initially):
$(document).ready(function() {
if (window.location.hash == '#images') {
$("#info").hide();
$("#displayImg").show()
$("#imageFlow").show();
}
else if (window.location.hash == '#info') {
$("#displayImg").hide();
$("#imageFlow").hide();
$("#info").show();
}
});
If all you're doing is setting text in the URL, you can do this easily by setting location.hash
location.hash="#SomeTextHereThatMayOrMayNotNecessarilyBeAnAnchor"
^ Note that "#" is important

Categories

Resources