jQuery - nth child and slider problem? - javascript

There is a generic image slider (nivo image slider) used on the charity pages that contains 7 slides, each slide is a different charity. I have used some jQuery so that when you are on a charities detail page, that specific charities slide shows up first in the slider queue; instead of it just looping from the start of the slider queue and showing a non-relevant charity. Basically looks at the URL and matches to the href in the slider link and adds a class then moves to the top of the link etc...
For example, these 2 work fine...
http://test.clothesaid.co.uk/partner-charities/yorkshire-cancer-centre/
http://test.clothesaid.co.uk/partner-charities/nspcc/
...they load their respective charities slider. However...
http://test.clothesaid.co.uk/partner-charities/papworth-hospital-charity/
...which is the oldest entry and at the bottom of the list won't load it's respective slider and just shows the slider list in it's normal order as the jQuery has not kicked in.
The charities are added in date order with the newest charity at the top of the list and the oldest charity at the bottom of the list. The jQuery works fine on all charities apart from whatever charity is at the bottom of the list, it just won't kick in. I'm sure it's something to do with the 'clone' slide that the Nivo slider uses and something to do with the :nth child in jQuery but I just can't work it out. That's the only thing that would make sense as the date order of the charities is the only thing that is changing. You can see the stack of charity logos on the right hand side of the page, that is the date order, with the oldest at the bottom. It's always the oldest one (at the bottom of the list) that won't work.
I'm basically stuck!
HTML
<ul id="slider1">
<li class="panel cloned">Example</li>
<li class="panel hello">Example</li>
<li class="panel">Example</li>
<li class="panel">Example</li>
<li class="panel">Example</li>
<li class="panel cloned">Example</li>
</ul>
jQuery
var url = window.location.toString();
$('#slider1 li.panel a').each(function(){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").addClass('hello').insertAfter("#slider1 li:nth-child(1)");
return false;
}
});

What's happening is that 'papworth-hospital-charity' is the first in the list of li and insertAfter will try to insert it after himself which is not working
I suggest that you check the index of the li before moving it (you are moving the target li to the 2nd position right?)
var url = window.location.toString();
$('#slider1 li.panel a').each(function(index){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").addClass('hello')
if(index==0){
$(this).closest("li").insertAfter("#slider1 li:nth-child(2)");
}else{
$(this).closest("li").insertAfter("#slider1 li:nth-child(1)");
}
return false;
}
});
or use anythingSlider ability to show slides by index:
var url = window.location.toString();
$('#slider1 li.panel a').each(function(index){
var myHref= $(this).attr('href');
if( url == myHref) {
$('#slider1').anythingSlider(index);
return false;
}
});

$(document).ready(function() {
var url = window.location.toString();
$('#slider1 li.panel a').each(function(){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").addClass('hello').insertAfter("#slider1 li:nth-child(1)");
return false;
}
});
};

Related

Keep active class on gallery navigation when using pagination

I have the following navigation on the gallery page of my website that allows users to filter the images by category.
<ul>
<li>All</li>
<li>Our Gym</li>
<li>Our Classes</li>
<li>Our Coaches</li>
</ul>
I've added the following snippet to add the class 'active' the category that is currently being viewed by the user.
<script>
jQuery(function($) {
var path = window.location.href;
$('.gallery_listing_wrapper li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
This works for the above gallery navigation however once I navigate using the pagination it doesn't work.
The URL for the pagination is slightly different to the gallery and its categories.
For example - instead of /gallery/our-gym/ - page/ and the page number is added to the URL i.e. /gallery/page/2/
Is it possible to adjust the above snippet to keep the active class on All when the pagination is being used?
You could always just add the class to the "All" button if none of the other buttons match the current URL.
<script>
jQuery(function($) {
var path = window.location.href;
let match = $(`.gallery_listing_wrapper li a[href="${path}"]`);
if(match.length >= 1)
match.addClass("active");
else
$(".gallery_listing_wrapper li a[href='/gallery/']").addClass("active");
});
</script>

Using a comparison table. Mobile responsive problem when more than one table added?

The comparison table I am using is here:
https://codepen.io/adrianjacob/pen/KdVLXY
When I duplicate the tables and the viewer goes mobile responsive; the buttons are only working for the first table.
Is there any classes or such I can add to the JavaScript and HTML so I can make each group of buttons specific to their table?
Button code:
<ul>
<li class="bg-purple">
<button>Self-Employed</button>
</li>
<li class="bg-blue">
<button>Simple Start</button>
</li>
<li class="bg-blue active">
<button>Essentials</button>
</li>
<li class="bg-blue">
<button>Plus</button>
</li>
JavaScript code:
// DIRTY Responsive pricing table JS
$( "ul" ).on( "click", "li", function() {
var pos = $(this).index()+2;
$("tr").find('td:not(:eq(0))').hide();
$('td:nth-child('+pos+')').css('display','table-cell');
$("tr").find('th:not(:eq(0))').hide();
$('li').removeClass('active');
$(this).addClass('active');
});
// Initialize the media query
var mediaQuery = window.matchMedia('(min-width: 640px)');
// Add a listen event
mediaQuery.addListener(doSomething);
// Function to do something with the media query
function doSomething(mediaQuery) {
if (mediaQuery.matches) {
$('.sep').attr('colspan',5);
} else {
$('.sep').attr('colspan',2);
}
}
// On load
doSomething(mediaQuery);
I'd really appreciate any help, thanks for your time.
The problem is that your jQuery targets are currently too generic, so when you have multiples, it only finds content from the first one and puts it in both. What your script does is update both tables.
I've forked the Codepen, added a second table, and tweaked a couple of values on our comparison table, so you should see different things in each (and each set of tabs acts separately)
https://codepen.io/CapnHammered/pen/QzBbqN
Key part you're missing is some form of parent selector - in this case, we've used an article tag to wrap our table:
$( "ul" ).on("click", "li", function() {
var pos = $(this).index()+2;
$parent = $(this).closest('article');
$parent.find("tr").find('td:not(:eq(0))').hide();
$parent.find('td:nth-child('+pos+')').css('display','table-cell');
$parent.find("tr").find('th:not(:eq(0))').hide();
$parent.find('li').removeClass('active');
$(this).addClass('active');
});
Try this:
$("ul").on("click", "li", function(e) {
var $clicked = $(e.currentTarget); // This will give you the clicked <li>
var $ul = $clicked.parent();
var $table = $ul.next(); // Only works if the table immediately follows the <ul>
var pos = $clicked.index() + 2;
$table.find("tr").find("td:not(:eq(0))").hide();
$table.find("td:nth-child(" + pos + ")").css("display", "table-cell");
$table.find("tr").find("th:not(:eq(0))").hide();
$clicked.siblings().removeClass("active");
$clicked.addClass("active");
});
Basically, when you click a <li> you should search the next table and show/hide the information only on that table. Before you were selecting all <tr> elements so it would affect all tables in the page.
EDIT: after re-reading your question this sentence left me confused:
When I duplicate the tables and the viewer goes mobile responsive; the buttons are only working for the first table.
When I try to duplicate the tables in your codepen the buttons work for both tables, not sure if I'm understanding your problem.

jquery scrollintoview with bootstrap scrollspy

Hello fellow stackoverflow members who use bootstrap! I appreciate your time and input. I am having trouble implementing a jQuery.scrollintoview with bootstrap scrollspy.
http://jsfiddle.net/aKK2k/1/
Above is fiddle, scrollspy is broken but the scrollintoview should still work, or am i mistaken?
Nav buttons that move the page:
<li>
<a href="#section-2" id="a-section-2">
Products
</a>
</li>
Below is the scroll-to-section
<h3 class="center" id="section-2">
So, how can Day & Night help your business today?
</h3>
Below is the JS that handles the page scrolling / hiding url / etc.
The implementation happens at
$($(this).attr('href'))[0].scrollIntoView(250, "easeOutExpo");
The whole JS
<script>
$("document").ready(function() {
$(document).on('click','.navbar li a',function(event) {
event.preventDefault();
if($.trim($(this).html())!='FAQ'){
//if($.trim($(this).html())!='FAQ' || $.trim($(this).html())!='FAQ2'){
var offset = $('#myNavbar').height()+30;
if ($(window).width() <= 768) {
var offset = 100;
}
$($(this).attr('href'))[0].scrollIntoView(250, "easeOutExpo");
scrollBy(0, -offset);
}
else
{
window.location.href = $(this).attr('href');
}
});
//document.referrer returns the url from which this page has been entered,
//we will use this to check if we are redirected from FAQs page
var previous_url = document.referrer;
if(previous_url=='http://dnwebdev.com/dev/faq/'){
//if we were redirected from FAQ page, we would have a #section-value in our url
//hash here fetched that value
var hash = document.URL.substr(document.URL.indexOf('#')+1);
//this is the important part, we are gonna trigger that the
//#section-value passed in url is _clicked_. And so the browser will
//scroll down to that section
$('.navbar li a#a-'+hash).trigger('click');
//once it scrolls down, this deletes the #section-value from url
history.pushState('', document.title, window.location.pathname);
}
});
function close_toggle() {
$('.nav a').on('click', function () {
if ($(".navbar-toggle").css("display") != "none") {
$(".navbar-toggle").click();
} else {
$('.nav a').off('click');
}
});
}
close_toggle();
$(window).resize(close_toggle);
</script>
Currently the page jumps when an "easeOutExpo" is what we are going for.
I am very new to JS, any input is appreciated.
The website is http://dnwebdev.com/
I added jqueryUI, declared jquery before ui, but the scroll still won't work.
Robert
You are invoking scrollIntoView on the raw DOM element, when you want to invoke it on the jquery matched set. Remove the [0] and try this:
$($(this).attr('href')).scrollIntoView(250, "easeOutExpo");
fiddle: http://jsfiddle.net/aKK2k/7/
(i've also added the jquery stuff to your fiddle).

How to keep the selected menu active using jquery, when the user comes back to page?

I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});

Change class of item when scrolled to

I have a nav set up that when a link is clicked, the page scrolls down to the corresponding item in a list, changing the class of the link when the item is reached.
<nav>
one
two </nav>
<ul>
<li id="one"></li>
<li id="two"></li>
</ul>
Here is a rather crude example
http://jsfiddle.net/FSk5Q/1/
I would also like to change the background colour of the item once it is reached (preferably fading to a new colour), and then restore it's original class when another item is scrolled to, then changing the next item's class.
I need this to happen when clicked to AND scrolled to, so the :target option is not really ideal.
Many thanks for an advice. Not too good in the js department.
Hopefully this can at least get you started. What I have done is check that the offset top is less than the document's scroll top (you could also do something like if it's within X number of pixels).
The color fading can be done with CSS3 transitions.
$(document).on('scroll', function () {
$("li").each(function () {
if ($(this).offset().top <= $(document).scrollTop()) {
$("li").removeClass('highlight');
$(this).addClass('highlight');
}
else {
$(this).removeClass('highlight');
}
});
});
http://jsfiddle.net/FSk5Q/6/
I did a fixed version based on Explosion Pills' one. Hope it's what you wanted.
$(document).on('scroll', function ()
{
$("nav a").removeClass('highlight'); // reset all menu items
temp = $();
$("li").each(function (i) // for each content blcok (you schould give them a class)
{
if ($(this).offset().top <= $(document).scrollTop()) // if it's position is above/at the page top
{
temp = $("nav a:nth-child("+(i+1)+")");
}
});
temp.addClass('highlight');
});
http://jsfiddle.net/maxmeuten/FSk5Q/8/

Categories

Resources