jQuery - addClasss to div depending on URL hash on page load - javascript

I have a page with team members and I need to add class to section based on the current hash in URL. The reason is to enable linking to specific team member as they don't have separate pages.
So when somebody enters URL https://www.mypage/members#anchorX the open class will be added to the element right after div with anchorX ID.
$(window).on('hashchange', function(e) {
e.preventDefault();
let hash = window.location.hash.substr(1);
$('div[id^="' + hash + '"]').next().addClass('open');
});
.open {
color: red;
opacity: 1
}
Bla
Bli
Blu
<div id="anchorX">Anchor 1</div>
<div>this should be red 1</div>
<div id="anchorY">Anchor 2</div>
<div>this should be red 2</div>
<div id="anchorZ">Anchor 3</div>
<div>this should be red 3</div>
The JS code above works fine but ONLY when the hash changes - so when somebody already is on the page https://www.mypage/members and then will go to the https://www.mypage/members#anchorX it works.
But I need that to be working mainly when somebody gets an URL with hash and going directly to https://www.mypage/members#anchorX. But in this situation nothing happens. As I understand it is because there is no 'hash change' in the second situation, but how can I make it work? Different window event? Or trigger some kind of reload?
https://jsfiddle.net/beatajak/de18hwxf/9/ - the code above

Just call it on load, and no need for preventDEfault
const changeColor = (e) => {
let hash = window.location.hash;
if (hash.length > 1) $(hash).next().addClass('open');
};
$(function() {
$(window).on('hashchange', changeColor);
changeColor()
})

Related

trying to make a link look different when page is clicked in html

well i have seen some similar questions but i couldn't find the solution i needed i am trying to make it so that when the user moves from one page to another in the website when the page is loaded the a tag should change color and stay that way i have tried using this code but it didnt work at all here is the html of the code
<div id="button-group" style="width:100%">
<img src="felix.png" id="cat" >
home
Hobbies
Contact
Services
</div>
so for example if i am on the Hobbies page and click the home page the home page should turn the color to blue or if i am on hobbies and its clicked it should also change color onload
here is the jquery that i tried
$(document).ready(function(){
$("#hobbies").trigger('.click');
});
and here is the css when triggered
.a :click {
background-color:rgba(0, 183, 255, 0.788);
}
You can use sessionStorage to store the link that was clicked and get it when the new page is loaded to set a class to the last clicked navigation element.
$(document).ready(function() {
let clicked = $.trim(sessionStorage.getItem("clicked"));
if (clicked) {
$("#button-group a").each(function() {
if ($.trim($(this).attr("href")) == clicked) {
$(this).addClass("clicked");
};
});
}
$("#button-group a").on("click", function() {
$("#button-group a").each(function() {
$(this).removeClass("clicked");
});
let link = $(this).attr("href");
$(this).addClass("clicked");
sessionStorage.setItem("clicked", link);
});
});
As a stack snippet for this doesn't work on Stackoverflow, here's a Fiddle with the adjustment to use preventDefault() on click of a link. Just run the Fiddle again after clicking on a link to see that the last clicked link gets added the class clicked.

Jump to top when click on links with hashtags + text

I have links with the following syntax:
<div class="footer">
Link 1
Link 2
Link 3
</div>
When I'm on the http://example.com/page and I click on any of the 3 links, it doesn't jump to the top of the page.
However, it jumps if the link is something like this:
Link 1
How should I make it scroll/jump to the top when any of the links are clicked?
You can set up a click event handler for all the elements you want to cause the scroll to occur using window.ScrollTo() like this:
// Get a node list of all the elements that use the footer class
var footers = document.querySelectorAll(".footer");
// Loop through the footers and set up a click event handler for each
for(var i = 0; i < footers.length; i++){
footers[i].addEventListener("click", function(e){
// Scroll to the top of the page:
window.scrollTo(0, 0);
});
}
<div class="footer">Link 1</div>
Link 2
<div class="footer">Link 3</div>

Jquery keep users on the page

Today i asked a question to which has been resolved but i am facing a very little browser problem that when when users open my link with the hash tag it divert them to the active div but i want to keep them on the top of the page
so the problem is when someone vist my website from this example link
mywebsite.com/mypage.html#page1
i dont want users to scroll down to the actived div but want to keep them on the top of the page
Here is my code
CSS:
.active {
color:red;
}
#menu_container div {
display:none;
}
HTML:
<div id="nav_tabbed">
<a href="#show_page1" class='active'>Page 1</a> <!--This lets you add hash in the addressbar-->
Page 2
</div>
<div id="menu_container">
<div id="show_page1" style='display:block;'>Page 1</div>
<div id="show_page2">Page 2</div>
</div>
JS:
$(function () {
var hash = location.hash;//hash added in the browser.
if(hash.length){
$('#nav_tabbed a').removeClass('active');
$('#menu_container div').hide();
$('#nav_tabbed a[href*="' + hash + '"]').addClass('active');
$('#menu_container div[id*="' + hash.slice(1) + '"]').show();
}
// below works for click of the anchors
$('#nav_tabbed a').click(function(e){
e.preventDefault();
$(this).addClass('active').siblings('a').removeClass('active');
$('#menu_container div').hide();
$('#menu_container div[id*="'+this.getAttribute('href').slice(1)+'"]').show();
});
});
Here is the reference link of my question: jquery tabs access from urls
Maybe
$(function(){
document.location.hash = ""
})
can work: after you have loaded your page, a internal link dont force reload..
One way of doing that could be adding a mock id and then changing to the true ID on document ready:
$("page1-mock").attr("id","page1");
Or you may do as suggested in other answers, so far all seem legit too.
When you visit mywebsite.com/mypage.html#page1 and there is an element with the id of page1 in the document you can't prevent the browser to scroll down to it. The easiest solution is to remove the element with the id. The ugly solution is to scroll to the top of the page with after load of the page
setTimeout(function() {
window.scrollTo(0, 0);
}, 0);

Setting default content of container when page loads/refresh then changes after click event fires

I am trying to set default content of a container when page loads/refresh, so that it does not look empty until click event that populates the container is fired.
The jQuery i'm working with looks like this
$(document).ready(function() {
$('[class^="question"]').on('click', function(e){
e.preventDefault();
var numb = this.className.replace('question', '');
$('[id^="answer"]').hide();
$('#answer' + numb).show();
});
});
My html makeup looks like this :
<div class="new_member_box">
<h4>Vision</h4>
</div>
<div class="new_member_box_display" id="answer1">
1
</div>
<div class="new_member_box_display" id="answer">
Default
</div>
When The page loads, Default text is shown, but when I clicked Vision link, 1 is shown then Default is shown in a box below it. What i want is that Default shows when page loads/refresh, then when a link is clicked default disappears and then the value for the clicked links is shown.
Also include $('[id^="answer"]').hide(); on dom ready..
$(document).ready(function(){
$('[id^=answer]').not('#answer').hide(); //add this
//click function code
});
Working jsFiddle
Lets break down your code:
$('[id^="answer"]').hide(); //This hids all the elements starting with answer as id
$('#answer' + numb).show(); // and show a particular answer
But the default content box in your demo has question as an id
<div id="question" class="new_member_box_display">
Text will appear here when one of the tabs above is clicked
</div>
So your script will not effect this part. A valid solution would be to add a class to represent this div as a default box. Something like
<div id="question" class="new_member_box_display default">
<!-- ^ I added a class here -->
Text will appear here when one of the tabs above is clicked
</div>
Then, in our script we will hide that first.
$(function() {
$('[class^="question"]').on('click', function(e){
e.preventDefault();
var numb = this.className.replace('question', '');
$('.default').hide(); // Lets hide that first
$('[id^="answer"]').hide();
$('#answer' + numb).show();
});
});

How do I use colorbox to show hidden divs on my page without hardcoding?

I'm using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
This will show the div with the ID of 344.
However, because I'm trying to build a scalable and dynamic page with WordPress, I want to be able to grab the ID of my divs through a function, rather than hard code them in the jquery call.
I modified Jack Moore's example:
$("a[rel='example']").colorbox({title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
so that it looks like this:
$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
var elementID = $(this).attr('id');
return elementID;
}});
The problem with this is that the href property of the colorbox function is looking for a string with a # mark infront of the ID. I tried various ways of concatenating the # to the front of the function, including the # in the return value, and concatenating the # to the elementID variable. No luck.
I also tried using the syntax in Jack's example (with no luck) so that my return statement looked like this:
return "#'+elementID+'";
I think my basic question is: How do I use colorbox to show hidden divs on my page without hardcoding everything?
Thanks for your help,
Jiert
I didn't really like any of the answers given above. This is how I did it (similar but not quite the same).
I also fully commented it for people a bit new to Javascript and the colorbox plug in.
$(document).ready(function() { //waits until the DOM has finished loading
if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
$('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
$(url).hide(); //hides the lightbox content div
$(this).colorbox({
inline:true, // so it knows that it's looking for an internal href
href:url, // tells it which content to show
width:"70%",
onOpen:function(){ //triggers a callback when the lightbox opens
$(url).show(); //when the lightbox opens, show the content div
},
onCleanup:function(){
$(url).hide(); //hides the content div when the lightbox closes
}
}).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
//you could also use "return false" for the same effect but I proffered that way
})
}
});
And this is the html:
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
I think it would work with multiple lightboxes on the one page but I haven't tested it with that.
I'm facing the same issue. What does your html look like? meaning, how did you structure your "divs"
Mine looks like this:
Javascript:
<script>
$(document).ready(function () {
$("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
var elementID = $(this).attr('id');
return "#" + elementID;
}
});
});
</script>
And the html looks like (I tried changing the display:none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
return "#" + elementID;
will have the desired effect as David says.
This is the way I got it to work
HTML: (taken from the example in one of the answers)
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
Javascript:
$('a.lightboxTrigger').click(function(){
var ref = $(this).attr("href");
$.colorbox({ html: $(ref).html() });
$.colorbox.resize();
});

Categories