Show toggling div based on URL - javascript

I'm trying to have an anchor link, once clicked, show a div. I have a click toggle working on the page, but in addition to that functionality, if a user clicks a sidebar link, I don't want the div to toggle, I just want it to be shown, if hidden. I've tried several if thens, etc - I think this is the closest, but still not working.
Functions (first toggles the h4, the second is my attempt to have the same div shown if a URL is loaded...or the anchor link is clicked):
<script>
$(document).ready(function(){
//Hide (Collapse) the toggle containers on load
$(".toggle_container3").hide();
//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
$(".trigger3").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
return false; //Prevent the browser jump to the link anchor
}).first().click()
});
</script>
<script>
$(function() {
if ( document.location.href.indexOf('#papers') > -1 ) {
$("#papertoggle").show();
$("h4#papers").addClass("active");
})
});
</script>
Also tried this version, with the keyword either "papers" or "climate_change_test#papers" :
<script type="text/javascript">
// Get URL
var url = window.location.href;
// Get DIV
var msg = document.getElementById('papertoggle');
// Check if URL contains the keyword
if( url.search( 'climate_change_test#papers' ) > 0 ) {
// Display the message
msg.style.display = "block";
}
</script>
HTML of the link:
<li>Papers and Publications</li>
HTML of the h4 and div:
<h4 class="trigger3 dark_grey" id="papers">
Papers and Publications</h4>
<div class="toggle_container3" id="papertoggle"> content </div>
Entire test page:
http://www.sea.edu/sea_research/climate_change_test

This should work:
$("#over_left a").click(function(){
var id = $(this).attr("href");
$(id).toggleClass("active").next().slideToggle("slow");
});
However I would suggest to narrow down the $("#over_left a") selector so it only works on those specific submenu links.
Also tried this version, with the keyword either "papers" or "climate_change_test#papers" :
<script type="text/javascript">
// Get URL
var url = window.location.href;
// Get DIV
var msg = document.getElementById('papertoggle');
// Check if URL contains the keyword
if( url.search( 'climate_change_test#papers' ) > 0 ) {
// Display the message
msg.style.display = "block";
}
</script>
The reason why the above code didn't work, is because it is executed on page load. However, when you click an anchor tag url, the page doesn't reload (it only jumps to the relevant anchor div), so this code is never executed.
Please also be aware that you don't need a complicated search to look for the "#papers" part in your url. You can simply use:
window.location.hash
To find the anchor part at the end of your url.
So combining all of the info from above, you can also create a function that deals with the following example: What if someone shares a link with an anchor url? It should automatically expand already then, right?
// On page load
var anchor = window.location.hash;
// If there is an anchor in the URL, expand the relevant div
if (anchor) {
$(anchor).toggleClass("active").next().slideToggle("slow");
}

Related

How to reuse my code for opening Accordions on click

I'm currently using the following JS to open an accordion when an <a> tag is clicked. It uses the data-trigger value to determine what <a> to use.
<script type="text/javascript">
$('[data-trigger="accordion"]').on('click', function(e) {
var obj = $(this),
accordionButtons = $('[href*="#"]', '[data-accordion] .accordion-navigation'),
accordionPanels = $('.content.1', '[data-accordion]');
if (obj.hasClass('toggle-open')) {
accordionButtons.removeClass('active');
accordionPanels.removeClass('active');
obj.removeClass('toggle-open');
} else {
accordionButtons.addClass('active');
accordionPanels.addClass('active');
obj.addClass('toggle-open');
}
$('[href*="#"]', '[data-accordion] .accordion-navigation').trigger('click.fndtn.accordion');
window.location.href = "#" + anchor;
e.preventDefault();
});
</script>
This above JS will open an accordion based on it's class. Below is an example of the link that is used to open the Accordion:
<a href="#protect-the-nhs" data-trigger="accordion">
An example of the code that it is referencing to open the accordion:
<div id="protect-the-nhs" class="content 1">
I was wondering if anyone can help me change this code so that I can reuse it for each Accordion on the page. Let me explain. The page has 5 different accordions, above I have used generic naming for the data-trigger and the accordion class "content 1".
I'd like to know if it is possible to somehow make it so I can use this code for each different accordion (So for example accordion 1 would have a class of "content 1", accordion 2 would have a class of "content 2" etc. However, for each accordion, there would also be a different link you have to click to open the accordion.
For example: Accordion one would rely on an <a> tag with data-trigger="accordion1" and it would open the accordion with class="content 1".
I hope someone understands my ask and might be able to help! I've tried looking for something for this but haven't found anything. I'm still learning JS so TIA.
Thanks.
My basic idea is to listen to the entire document, determine where got clicked and activate the correct accordion
PLEASE NOTE: I'm assuming that every accordion has a number right after it that corresponds to the content classes like accordion1 content 1
document.onclick=function(e) {
if(!e.path[0].dataset.trigger){return;} //i forgot that not every element has a data-trigger
if(!e.path[0].dataset.trigger.startsWith('accordion')){return;} //listening to the whole document needs you have to ensure you aren't activating when you don't need to
var n=e.path[0]["data-trigger"].split('accordion')[1]
alert(n)
var obj = e.path[0],
accordionButtons = $('[href*="#"]', '[data-accordion] .accordion-navigation'),
accordionPanels = $(`.content.${n}`, '[data-accordion]');
if (obj.hasClass('toggle-open')) {
accordionButtons.removeClass('active');
accordionPanels.removeClass('active');
obj.removeClass('toggle-open');
} else {
accordionButtons.addClass('active');
accordionPanels.addClass('active');
obj.addClass('toggle-open');
}
$('[href*="#"]', '[data-accordion] .accordion-navigation').trigger('click.fndtn.accordion');
window.location.href = "#" + anchor;
e.preventDefault();
}

jQuery Event Delegation for certain links

I'm having trouble delegating a click function to only certain links. Essentially, I'm trying to trigger a simple fadeout for all internal links that won't kill a lightbox functionality. Here's my problem (in essence):
HTML
<body>
<div id="fade">
<p>some content</p>
</div>
</body>
jQuery
$("#fade").on("click", "a", function () {
// get the href attribute
var newUrl = $(this).attr("href");
// veryfy if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page)
$("body").fadeOut(function () {
// when the animation is complete, set the new location
location = newUrl;
});
// prevent the default browser behavior.
return false;
});
I can't figure out why this isn't working. The function isn't executed on any links. I'm trying to delegate it to all links within the wrapper id of "fade."
When I change
$("#fade").on("click", "a", function () {
to
$("document").on("click", "a", function () {
//specifying all links
The fade works perfectly, but it destroys the lightbox function that is needed for the site.
Is there a better way to delegate links for this event? Or perhaps not include the lightbox links in a different manner? Ideally I would keep the code above for executing on all links using $("document") and exclude the lightbox gallery from the function, but I don't know how I could do that.

How to open current page in new tab and reveal hidden div

Is it possible to click a button to open the same page in a new tab and reveal a hidden div that wasn't seen in the parent?
Currently I have a div called replacediv, that is being replaced with Replacement Text below when users click on the button...But it is being replaced in the parent. For my purpose, I would like to load this same page in a new tab, with the page content and the Replacement Text showing instead of the hidden replacediv.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#replacediv").replaceWith("<span class='style'>Replacement Text</span>");
});
});
</script>
<div id="replacediv"></div>
if you want the content of $("#replacediv") and the span in the same page not replacing one another you do this:
$(document).ready(function(){
$("#replacediv").before("<span style="display:none;" class='style'>Replacement Text</span>");
$("button").click(function(){
$(".style").show();
});
});
I think one way to do it, is when you open the page and add a URL-parameter, which causes the page to render differently, e.g. to replace some text on it, with the Text in the URL-parameter. e.g.
On your page, you define something like this:
$(document).ready(function(){
$("button").click(function(){
window.open(window.location.href + '?replace=Replacement%20Text', '_blank');
});
});
Additionally you need something like this (still in the same page, but active, only when called with a parameter)
$(document).ready(function(){
$("button").click(function(){
window.open(window.location.href + '?replace=Replacement%20Text', '_blank');
});
var arr = location.href.match(/replace=([^&]+)/)
var replace = arr[1];
if (replace != '') {
$("#replacediv").replaceWith("<span class='style'>" + replace + "</span>");
}
});
This version will leave your button still clickable. If you rather do not want a button, you need to ask for the URL parameter earlier and don't render your button in the first place. That is up to you.
Does it go in the right direction? Hope that helps.

How to prevent links to anchors in a child div from affecting main url?

Consider the following snippet:
<div id="help"></div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var loadPage = function (){
$("#help").load("http://localhost:3000/manual.html");
}
onload=loadPage;
</script>
This exists on my main page:
http://localhost:3000/
The above code works fine and loads my manual page. But if I click a link like this in manual.html:
<a href='#introduction'>Introduction</a>
Then the page in the help div jumps to the #introduction section, however the url in my browser updates to:
http://localhost:3000/#introduction
This is pointless because the #introduction anchor only exists in manual.html, how can I prevent the links in the #help div from affecting the address bar in the browser?
Try this
$('a').click(function(e) {
e.preventDefault();
$("#help").load($(this).attr('href'));
})
By using offset and preventDefault
$('a').click(function(e) {
// Go to '#introduction'
var targetId = $(this).attr('href');
$('html, body').offset({ top: $(targetId).offset().top, left: 0 });
// this prevent 'http://localhost:3000/#introduction'
e.preventDefault();
});
See this post
I already had a function that could scroll the #help window to a heading, when you click on objects in the parent it scrolls to the relevant section in the help window:
var moveTo = function(destination){
//position of the top of the help window - does not change.
var helpWindow = $("#help").offset().top;
//difference between current scroll position and target position.
var relativeDistance = $(destination).position().top - helpWindow;
//add the distance from current position to the top to get distance to target from top
var absoluteDistance = relativeDistance+ $("#help").scrollTop();
$("#help").animate({
scrollTop: absoluteDistance
}, 1000);
}
Using e.preventDefault() I was able to use this function to do what I want.
For others heading down this path there are two other small things to consider.
Firstly, make sure you nest the .click() function inside the callback from page load, as the hyper links won't exist until the page is loaded. Secondly, You will probably want to use a child selector eg $('#help a').click() to ensure you are only altering the behaviour on links inside the child.
$("#help").load("http://localhost:3000/manual.html", function(){
$('#help a').click(function(e) {
e.preventDefault(); //suppress standard link functionality
moveTo($(this).attr('href')); //scroll to link instead.
})
});

Javascript fadeIn div tags fails on click

Im kind of new to javascript, and I have tried for several hours now to make this fadeIn function to work.
First of all, look at my code here.
I have also included the following in my header:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
This is how I want the page to work,
When a user enters the site, the home selection will fadein
The menu is based on <ul> and <li> itmes for categories and in each category we have different comapnies. Each category have a <a href="category-id"> and each company have a <a href='company-id'> to the div tag made later in the body.
A user should be able to switch between the menu options, and each time the time should fade in.
So the problem as you see in my code, it works on page load, but I cant choose anything from the menu.
Any suggestions would be helpful
If I understood correctly you wanted it to function something like this :
$('#menu a').click(function () {
$("#content div").hide(); //Hide all content
var id = $(this).attr('href');
$(id).fadeIn(); // Show content for current tab
});
You didn't need this line (it is deleting the id) :
$("#menu li").attr("href", ""); //Reset id's
This is line I don't even know what it's for:
$(this).parent().attr("href", "current"); // Activate this google parent!
If you want to add a class to the current active menu item, use something like
$(this).parent().addClass('active');
Also you don't need to add '#' because you already had that in you href atrribute:
$($(this).attr('href')).fadeIn(); // Show content for current tab
You can check what kind of id you're getting by alerting it or logging it :
var id = $(this).attr('href');
alert(id);
$(id).fadeIn();
Are you sure with this line of Code?
$("#menu li").attr("href", "");
You do not override your ID here. You remove your link href.
you are resetting the "href" attribute. Thus, when you try to make a fadeIn the "href" attribute value is changed to "current".
Those two lines:
$("#menu li").attr("href", ""); //Reset id's
....
$('#' + $(this).attr('href')).fadeIn();
are wrong because $(this).attr('href') is equal to "" (empty string)
also you made a mistake because you did
$("#content div:last").fadeIn(); // Show first tab content
but the command and what you expect are not coherent. Here you are using fadeIn on the last tab content instead of the first.
You can try something like this: http://jsfiddle.net/546Jn/4/
$(document).ready(function () {
$("#content div").hide();
$("#content div:first").fadeIn(); // Show first tab content
$('#menu a').click(function () {
$("div#content div").hide(); // Hide all pages
$('div' + page).fadeIn(); // Show content for current tab
});
});

Categories