Help With URL parameter to open tabs info - javascript

Need some help with the script below. I would like to add the ability to pass a url parameter that would open one of the tabs based on the URL#tabinfo. Any help would be great thanks.
(function ($) {
function getactTabAnc() {
return this.find('.active>a')[0];
}
function getContentId(tabAnchorS) {
return $(tabAnchorS).attr('href').replace('#', '');
}
function applyStyles(newActTabAnc) {
var actTabAnc = newActTabAnc || getactTabAnc.apply(this), activeContentId = getContentId(actTabAnc);
this.find('a').each(function () {
var $cur = $(this), curContentId = getContentId(this);
if (activeContentId === curContentId) {
$cur.closest('li').addClass('active');
$('#' + curContentId).show();
}
else {
$cur.closest('li').removeClass('active');
$('#' + curContentId).hide();
}
});
}
$.fn.tabs = function () {
return this.each(function () {
var $tabTainer = $(this);
applyStyles.apply($tabTainer);
$tabTainer.find('a').click(function (e) {
console.log('clicked');
var actTabAnc = getactTabAnc.apply($tabTainer), isActive = this === actTabAnc;
e.preventDefault();
if (!isActive) {
applyStyles.apply($tabTainer, [this]);
}
});
});
};
})(jQuery);
<ul id="tabsHolder">
<li class="active">Header 1</li>
<li>Header 2</li>
</ul>
<div id="tabId1">Content 1</div>
<div id="tabId2">Content 2</div>

Look at window.location.hash and onhashchange event. If ('onhashchange' in window) is false then you need to poll for the hash changing.
There exists libraries to abstract this away.

Related

How do I make layer popup more accessibility?

I just made layer popup and I want to make it more accessibility.
This is what I tried so far
<p>Open layer1</p>
<p>Open layer2</p>
<div id="target" class="hidden">
layer1
<button class="close">clos</button>
</div>
<div id="target2" class="hidden">
layer2
<button class="close">clos</button>
</div>
$(document).ready(function() {
$.fn.layerOpen = function(options) {
return this.each(function() {
var $this = $(this);
var $layer = $($this.attr('href') || null);
$this.click(function() {
$layer.attr('tabindex',0).show().focus();
$layer.find('.close').one('click',function () {
$layer.hide();
$this.focus();
});
});
});
}
$('.layer').layerOpen();
});
Can any one have an idea for more accessible code ? Or any examples ?
Thank you.
Avoid to bind multiple click events. Also use hash property instead of href-attribute.
I suggest you do something like this:
$.fn.layerInit = function(options) {
return this.each(function() {
var $this = $(this), hash = $this.prop('hash'), $layer;
if (hash) {
$layer = $(hash).attr('tabindex', 0);
$this.on('click.layer', function() {
$layer.show().focus();
});
$layer.find('.close').on('click.layer', function() {
$layer.hide();
$this.focus();
});
}
});
};
$(document).ready(function() {
$('.layer').layerInit();
});
Avoid using loops and in-lining events
I suggest you do something like this:
$(document).ready(function() {
$.fn.layerOpen = function(options) {
var $this = $(this);
var layer = null;
$this.click(function() {
layer = $(this).attr('href') || null;
$(layer).attr('tabindex',0).show().focus();
});
$layer.find('.close').one('click',function () {
$(layer).hide();
$('[href="'+layer+'"]').focus();
});
}
$('.layer').layerOpen();
});

jQuery toggle menu items and sheet

I have written code that works very well, but unfortunately it is not perfect functional. I will describe briefly the action:
When I click on '.navbar-nav li a' parent and '.sheets, .sheetsBg' get active class.
If I click again '.navbar-nav li a' is properly removed only for the menu item parent class.
code:
function manageSheetsToggle() {
var navMenuItem = '.navbar-nav li a';
$(navMenuItem).click(function (e) {
if (!isTabletResolution() && !isPhoneResolution()) {
{
var sheetId = $(this).parent().data('target');
if ($('.sheets, .sheetsBg').hasClass('active')) {
$('.sheets, .sheetsBg').removeClass('active');
}
e.preventDefault();
$(this).parent().toggleClass('active').siblings().removeClass('active');
$("#" + sheetId).toggleClass('active').siblings().removeClass('active');
$(".sheets, .sheetsBg").addClass("active");
}
} else {
$(navMenuItem).click(function (e) {
e.preventDefault();
location.href = $(this).attr('href');
}
);
}
});
$('.sheetsBg, .corpoBelt, .header').click(function () {
$(".sheets, .sheetsBg").removeClass("active");
});
}
pls help.
I hope this is what you are luking for. I changed your code a little bit, but it works fine now. Try it and let me know
<script type="text/javascript">
var sheet, ln, cn = 0;
$(document).ready(function () {
$("#toggleMenu").find("a").on("click", function (e) {
ln = $(this);
sheet = ln.parent().data('target');
$("#" + sheet).toggleClass("active").siblings().removeClass('active');
$(".sheets").find("section").each(function () {
if ($(this).hasClass("active"))
cn++;
});
if (cn) {
$(".sheets").addClass('active');
cn = 0;
} else
$(".sheets").removeClass('active');
});
$('.corpoBelt').click(function () {
$(".sheets").removeClass("active");
});
});
</script>
I think you can use siblings() selector more easier
https://jsfiddle.net/2q50kj3a/1/

jQuery - Toggle text to change on click

I have a menu button, which when clicked will slide down a div below.
My menu is title "+ Open menu"
When the menu button is clicked my code changes the title to "+ Menu" to indicate that the menu is open.
When the user closes the menu I would like the title to revert back to "- Menu"
This is my HTML which defines the class, test in this case.
<span class="test">+ Open menu</span>
Here is my jQuery function, I cannot figure out how to revert the menu state.
$(document).ready(function () {
$(".widget_head_type").click(function ()
{
$(".widget_body_type").slideToggle("slow");
$(".test").text("- Close menu");
});
});
$(".widget_head_type").click(function () {
$(".widget_body_type").slideToggle("slow");
($(".test").text() === "+ Open menu") ? $(".test").text("- Close menu") : $(".test").text("+ Open menu");
});
jQuery.fn.extend({
toggleText: function (a, b){
var that = this;
if (that.text() != a && that.text() != b){
that.text(a);
}
else
if (that.text() == a){
that.text(b);
}
else
if (that.text() == b){
that.text(a);
}
return this;
}
});
Use as:
$("#YourElementId").toggleText('After', 'Before');
Here is an interesting one based on the http://api.jquery.com/toggle/
HTML
<span class="test">+ Open menu</span>
<span class="test" style="display:none">- Close menu</span>
JS
$(document).ready(function () {
$(".widget_head_type").click(function ()
{
$(".widget_body_type").slideToggle("slow");
$(".test").toggle();
});
Simple, just toggles the all tags with class test whether hidden or visible.
WORKING FIDDLE HERE
I've guessed at your html, and made some notes for alternatives, but you consider the following:
HTML:
<div class="some_parent_class">
<div class="widget_head_type">
<span class="test">+ Menu</span>
</div>
<div class="widget_body_type">
Body
</div>
</div>
JS:
jQuery(function ($) {
$('.widget_head_type').each(function () {
// closures
var $toggle = $(this);
var $parent = $toggle.closest('.some_parent_class');
var $target = $parent.find('.widget_body_type');
var $label = $toggle.find('.test');
var bIsTweening = false;
// OR var $target = $toggle.next('.widget_body_type');
// event methods (closures)
var fClickToggle = function () {
if (!bIsTweening) {
bIsTweening = true;
$target.slideToggle('slow', fToggleCallback);
}
};
var fToggleCallback = function () {
bIsTweening = false;
fSetLabel();
};
var fSetLabel = function () {
var sLabel = $label.text().replace('+', '').replace('-', '');
sLabel = ($target.is(':visible') ? '-' : '+') + sLabel;
$label.html(sLabel);
};
// handle event
$toggle.click(fClickToggle);
$target.hide();
fSetLabel();
});
});
had same issue and this is how i solved it: using your code example.
$(".widget_head_type").click(function () {
$(".widget_body_type").slideToggle("slow");
($(".test").text() == "+ Open menu") ? $(".test").text("- Close menu") : $(".test").text("+ Open menu");
});
use two equal signs for comparison.

Add Active Navigation Class Based on URL

I'm trying to add an active class (i.e. class="active") to the appropriate menu list item based upon the page it is on once the page loads. Below is my menu as it stands right now. I've tried every snippet of code I could find in this regard and nothing works. So, can someone please explain simply where and how to add in javascript to define this task?
<ul id="nav">
<li id="navhome">Home</li>
<li id="navmanage">Manage</li>
<li id="navdocso">Documents</li>
<li id="navadmin">Admin Panel</li>
<li id="navpast">View Past</li>
</ul>
Here is an example of the javascript that I'm putting in my head tag in my site master. What am I doing wrong?
$(document).ready(function () {
$(function () {
$('li a').click(function (e) {
e.preventDefault();
$('a').removeClass('active');
$(this).addClass('active');
});
});
});
The reason this isn't working is because the javascript is executing, then the page is reloading which nullifies the 'active' class. What you probably want to do is something like:
$(function(){
var current = location.pathname;
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
.active, a.active {
color: red;
}
a {
color: #337ab7;
text-decoration: none;
}
li{
list-style:none;
}
<h3>Add Active Navigation Class to Menu Item</h3>
<ul>
<li>Home</li>
<li>About</li>
</ul>
<h2>Live Demo</h2>
With VANILLA plain JavaScript
(function () {
var current = location.pathname.split('/')[1];
if (current === "") return;
var menuItems = document.querySelectorAll('.menu-item a');
for (var i = 0, len = menuItems.length; i < len; i++) {
if (menuItems[i].getAttribute("href").indexOf(current) !== -1) {
menuItems[i].className += "is-active";
}
}
})();
ES6 version, that works properly in cases when your link is to "/products" and you have subroutes, like: "/products/new", "/products/edit", etc.
let switchNavMenuItem = (menuItems) => {
var current = location.pathname
$.each(menuItems, (index, item) => {
$(item).removeClass('active')
if ((current.includes($(item).attr('href')) && $(item).attr('href') !== "/") || ($(item).attr('href') === "/" && current === "/")){
$(item).addClass('active')
}
})
}
$(document).ready(() => {
switchNavMenuItem($('#nav li a, #nav li link'))
})
If your menu need add the active class in li, you need use this code above.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).closest('li').addClass('active');
}
});
});
$(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
$( ".top-menu li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd)
$(this).addClass('active')
});
});
This on page JS code is a 100% working put your id and enjoy it.
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
console.log(CurrentUrlEnd);
$( "#lu-ID li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd){
$(this).closest('li').addClass('active')
}
});
});
None of the above solutions worked for me. Finally this javascript solution worked.
<script>
function setActive() {
linkObj = document.getElementById('premier-topnav').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
if(document.location.href.indexOf(linkObj[i].href)>=0) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
</script>
premier-topnav is the id of navbar div.
.active class is defined as:
#premier-topnav .active {
color: brown;
}
var cururl = window.location.pathname;
var curpage = cururl.substr(cururl.lastIndexOf('/') + 1);
var hash = window.location.hash.substr(1);
if((curpage == "" || curpage == "/" || curpage == "admin") && hash=="")
{
//$("nav .navbar-nav > li:first-child").addClass("active");
}
else
{
$(".topmenu li").each(function()
{
$(this).removeClass("active");
});
if(hash != "")
$(".topmenu li a[href*='"+hash+"']").parents("li").addClass("active");
else
$(".topmenu li a[href*='"+curpage+"']").parents("li").addClass("active");
}
Rob.M got it right.
I'm just going to post my solution since his didn't really work for me. i have a small change in comparison to him. assuming you have different paths to each link.
(function() {
var current = location.pathname;
$('#navbar ul li a').each(function() {
var $this = $(this);
// we check comparison between current page and attribute redirection.
if ($this.attr('href') === current) {
$this.addClass('active');
}
});
})();
This worked perfectly for me.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).addClass('active');
}
});
});
I know it been quite a while this question was asked. Here is the answer which will work without jQuery:
var activeNavlink = document.querySelectorAll('nav a[href^="/' + location.pathname.split("/")[1] + '"]');
activeNavlink[0].classList.add('active');
Hope this helps.
If you want for master page in asp .net just put this code inside body tag
<script type="text/javascript">
jQuery(function ($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function () {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
Thank you
This should do your job in one liner.
document.querySelector(`a[href^='${location.pathname.split('/'[1])}']`).className = 'active'
jQuery style:
$('a[href="'+ window.location.href + '"]').css({
backgroundColor: 'red',
color: 'white'
})
In first line use this if you have relative links
$('a[href="'+ window.location.path + '"]').css({
Or both
$('a[href="'+ window.location.href + '"], a[href="'+ window.location.path + '"]').css({
$(function(){
//this returns the whole url
var current = window.location.href;
//this identifies the list you are targeting
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is exactly like this link, make it active
if($this.attr('href') === current){
//this takes care of ul inside a ul, it opens and make active the selected li
$this.parents('.dropdown-menu').toggle();
$this.css('color', 'red');
}
})
});
The bellow jquery script will match the manu if the page has any query string parameter as well. This script is helpful for links with nearly same name.
<script>
//select current menu Item
$(function () {
var current = location.pathname.toLocaleLowerCase();
$('.sidebar li a').each(function () {
var $this = $(this);
var href = $this.attr('href');
href = href.replace(/\?.*/, "").toLocaleLowerCase();
// if the current path is equal to this link, make it active
if (href === current) {
$this.addClass('active');
}
})
})
</script>
Accessible Version:
Here's an accessible version inspired by rob.
I didn't want to run this script on the homepage so I check if it's the homepage
I check if the link matches the exact page instead of checking if it's included in the path. Or else you would get multiple items in the query.
JS
function activateCurrentPage(menuItems){
var current = location.pathname;
if (current !== "/") {
menuItems.each(function(){
var $this = $(this);
if($this.attr('href') === current){
$this.addClass('active');
$this.attr('aria-current', 'page');
}
});
};
}
activateCurrentPage( $('#nav li a') );
CSS
Then for CSS don't target the active class instead target the aria attribute.
#nav a[aria-current="page"]{
color:red;
}
Saw somethng wth plain Javascript
https://www.youtube.com/watch?v=BI3kNsTruWo&ab_channel=OnlineTutorials
Put it in <script> tags after header in my Wordpress site
(function () {
const currentLocation = location.href;
console.log(currentLocation);
const menuItem = document.getElementsByClassName('nav-item');
const menuLength = menuItem.length
for ( i = 0; i < menuLength; i++){
if(menuItem[i].href === currentLocation){
menuItem[i].className += " active"
}
}
})();
<a class="nav-item" href="/ideja/">Ideja</a>
<a class="nav-item" href="/piesaki-sapni/">Piesaki Sapni</a>
<a class="nav-item" href="/uznemejiem/">Uzņēmējiem</a>
<a class="nav-item" href="/sapnu-banka/">Sapņu banka</a>
<a class="nav-item" href="/sapnus-atbalsta/">Sapņus atbalsta</a>
<a class="nav-item" href="/99-iedvesmas-stasti/">99 iedvesmas stāsti</a>
<a id="lv" class="active" href="#">LV</a>
<a href="javascript:void(0);" class="icon" onclick="openNavbar()">
<div id="hamburger" class="hamburger "></div>
</a>
i was having troubles where the link to the root would light up if any page was selected when using Networker's example. this will prevent that for the root pae:
function setActive() {
linkObj = document.getElementById('menu').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
const url = new URL(window.location.href);
if((document.location.href.indexOf(linkObj[i].href)>=0 && linkObj[i].href != url.protocol+"//"+url.hostname+"/") || document.location.href == linkObj[i].href) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
This Does the Job Done For me...
Put this before the ending of body tag
$(function () {
var current = location.pathname;
console.log(current);
if (current == "/") {
$('#home').addClass('active'); //#home is the id for root link.
}
else {
$('#navbarCollapse div a').each(function () {
var $this = $(this);
// if the current path is like this link, make it active
if ($this.attr('href').indexOf(current) !== -1) {
$this.addClass('active');
}
})
}
})
Classes can make the life a whole way easier.
css
<nav>
<ul class="nav-list">
<li class="nav-list-item"><a class="nav-link nav-link-active" href="index.html">Home</a></li>
<li class="nav-list-item"><a class="nav-link" href="about.html">About Me</a></li>
<li class="nav-list-item"><a class="nav-link" href="posts.html">Recent Posts</a></li>
</ul>
</nav>
js
(function() {
current_page = window.location.href;
navlinks = document.getElementsByClassName("nav-link");
active_page = document.getElementsByClassName("nav-link-active")[0];
if (active_page) {
active_page.classList.remove("nav-link-active");
}
for (i=0; i < navlinks.length; i++) {
if (navlinks[i].href == current_page) {
navlinks[i].classList.add("nav-link-active");
break;
}
}
})();
I know this is late answer but this works ok for me
var links = document.querySelectorAll('li a');
for (link of links) {
if (window.location.pathname == link.getAttribute('href')) {
link.classList.add('active')
} else {
link.classList.remove('active')
}
}
Below is the solution to add the dynamic active class to the navbar elements.
// first lets get all the navbar elements.
const navElements = document.querySelectorAll(".list");
// creating a function of active navbar item
const activeLink = (el) => {
list.forEach((item) => {
item.classList.remove("active");
el.classList.add("active");
});
};
// attaching the event listener for each element
list.forEach((item) => {
item.addEventListener("click", () => {
activeLink(item)
});
});

Custom styled checkbox not working properly

Currently I'm using multiple blocks of the following code as my custom styled checkbox:
<div class="row-fluid">
<div class="span12 card card-even">
<div>
<h3><label class="checkbox">
<i class="icon-check-empty"></i>
<input type="checkbox" value="1" />
</label></h3>
</div>
</div>
</div>
The JS:
jQuery.fn.extend({
shinyCheckbox: function() {
var setIcon;
setIcon = function($el) {
var checkbox, iclass;
checkbox = $el.find("input[type=checkbox]");
iclass = "";
if (checkbox.is(":checked")) {
iclass = "icon-ok";
} else {
iclass = "icon-check-empty";
}
return $el.find("i[class^=icon-]").removeClass("icon-check").removeClass("icon-check-empty").addClass(iclass);
};
this.find("input[type=checkbox]").change(function() {
return setIcon($(this).parents("label.checkbox"));
});
return this.each(function(i, el) {
return setIcon($(el));
});
}
});
$(document).ready(function() {
return $("label.checkbox").shinyCheckbox();
});
Im able to achieve my requirement by styling the icon-check-empty & icon-check classes but when i click any checkbox only the first checkbox gets activated.
How can i use the this keyword to solve the issue such that the correct checkbox is activated?
This is the way I'd do it, based on your code:
jQuery.fn.extend({
shinyCheckbox: function () {
var setIcon = function ($el) {
var checkbox = $el.find("input[type=checkbox]"), checked = checkbox.is(':checked');
checkbox.val(+checked);
return $el.find("i[class^=icon-]").removeClass("icon-check-empty icon-ok").addClass(function () {
return checked ? "icon-ok" : "icon-check-empty";
});
};
this.find("input[type=checkbox]").on('change', function () {
return setIcon($(this).closest("label.checkbox"));
});
return this.each(function (i, el) {
return setIcon($(el));
});
}
});
$(document).ready(function () {
$("label.checkbox").shinyCheckbox();
});
The main issue was that you weren't removing the icon-ok class, only the icon-check class. I also cleaned the code up a little.
Here it is working: http://jsfiddle.net/W88fk/1/
you can try
jQuery.fn.extend({
shinyCheckbox: function() {
return this.each(function() {
var el=$(this),checkbox = el.find("input[type=checkbox]");
checkbox.change(function() {
var iclass = checkbox.is(":checked")?"icon-ok":"icon-check-empty";
el.find("i[class^=icon-]").removeClass().addClass(iclass);
var cval= checkbox.is(":checked")?0:1;
checkbox.val(cval);
});
});
}
});
$(document).ready(function() {
$("label.checkbox").shinyCheckbox();
});
toogle class and value http://jsfiddle.net/rWFMm/1/

Categories

Resources