jQuery if..else conditional statements based on hash id extracted - javascript

I have the following HTML:
<section>
<div class="main" id="second"> </div>
</section>
<section>
<div class="main" id="third"></div>
</section>
<section>
<div class="main" id="fourth"></div>
</section>
And following jQuery code:
<script>
navlist = [];
$("#navlist a").each(function(i) {
var thisLink = $(this);
var thisId = thisLink.attr('href');
var thisTarget = $(thisId);
navlist.push({
'anchor': thisLink,
'id': thisId,
'target': thisTarget
});
thisLink.on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: thisTarget.offset().top
}, 800);
});
});
$(window).on('scroll resize', function(e) {
$.each(navlist, function(e, elem) {
var placement = elem.target[0].getBoundingClientRect();
if( placement.top<window.innerHeight && placement.bottom>0 ) {
history.pushState({}, '', elem.id);
console.log('Hash: ' + elem.id);
return false; /* Exit $.each loop */
};
});
});
</script>
The work of the script is to allow smooth scrolling between different anchors on the site and to change URL #id on click or on scroll. I want to use here conditional statements with the id grabbed from the URL.
For example:
if(grabbedhashid == "second"){
$(".phone").css('display', 'none');
}else{
//display
}
But I am not having any idea as from where I can do it. Please help me guys.
Example URL with ID: http://localhost/sites/fh/index.php#first

So basically you have it in your scroll function, use that script to hide phone only in #second, it will work for you
$(window).on('scroll resize', function(e) {
$.each(navlist, function(e, elem) {
var placement = elem.target[0].getBoundingClientRect();
if (placement.top < window.innerHeight && placement.bottom > 0) {
history.pushState({}, '', elem.id);
console.log('Hash: ' + elem.id);
if(elem.id == "#second"){
$(".phone").css('display', 'none');
}else{
$(".phone").css('display', 'block');
}
return false; /* Exit $.each loop */
};
});
});

If you want to get current browser url at the time of scroll/click, you can get them as below. Use some string filter function like(window.location.href.split("#");) if you want to filter out only #id part.
JavaScript :
//using href
var URL = window.location.href;
//using path
var URL = window.location.pathname;
Jquery :
$(location).attr('href');

Related

Item soft rejected due to Proper Event Binding issue

An item I've submitted to themeforest.net got soft rejected with the following message:
PROPER EVENT BINDING: Consider using the preferred .on() method rather than .click(), .bind(), .hover(), etc. For best performance and concise code use event delegation whenever possible
I have no idea what to do actually and would appreciate some help.
This is my code (it’s quite long sorry):
jQuery(document).ready(function($) {
"use strict";
// PRELOADER
$(window).load(function() {
$('#preloader').fadeOut('slow', function() {
$(this).remove();
});
});
// NAV BR RESIZING
$(document).on("scroll", function() {
if ($(document).scrollTop() > 50) {
$("header").removeClass("large").addClass("small");
} else {
$("header").removeClass("small").addClass("large");
}
});
// MOBILE MENU TRIGGER
$('.menu-item').addClass('menu-trigger');
$('.menu-trigger').click(function() {
$('#menu-trigger').toggleClass('clicked');
$('.container').toggleClass('push');
$('.pushmenu').toggleClass('open');
});
// SEARCH
$('.search').click(function(e) {
$(".search-overlay").addClass("visible");
e.preventDefault();
});
$('.close-search').click(function(e) {
$(".search-overlay").removeClass("visible");
e.preventDefault();
});
// FOUNDATION INITIALIZER
$(document).foundation();
// LIGHTCASE
$('a[data-rel^=lightcase]').lightcase({
showSequenceInfo: false,
});
// CONTDOWN
$('[data-countdown]').each(function() {
var $this = $(this),
finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('' +
'<span class="time">%D <span>days</span></span> ' +
'<span class="time">%H <span>hr</span></span> ' +
'<span class="time">%M <span>min</span></span> ' +
'<span class="time">%S <span>sec</span></span>'));
});
});
// SCROLLDOWN BUTTON
$(".show-scrolldown-btn").append("<div class='scrolldown-btn reveal-from-bottom'></div>")
$('.scrolldown-btn').on('click', function() {
var ele = $(this).closest("div");
// this will search within the section
$("html, body").animate({
scrollTop: $(ele).offset().top + 70
}, 500);
return false;
});
// ISOTOPE MASONRY
$(window).load(function() {
var $container = $('.grid');
$container.isotope({
itemSelector: '.grid-item',
columnWidth: '.grid-sizer',
});
var $optionSets = $('.filter'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function() {
var $this = $(this);
if ($this.hasClass('active')) {
return false;
}
var $optionSet = $this.parents('.filter');
$optionSet.find('.active').removeClass('active');
$this.addClass('active');
// make option object dynamically, i.e. { filter: '.my-filter-class' }
var options = {},
key = $optionSet.attr('data-option-key'),
value = $this.attr('data-option-value');
value = value === 'false' ? false : value;
options[key] = value;
if (key === 'layoutMode' && typeof changeLayoutMode === 'function') {
changeLayoutMode($this, options);
} else {
$container.isotope(options);
}
return false;
});
});
//BACK TO TOP
var offset = 300,
offset_opacity = 1200,
scroll_top_duration = 700,
$back_to_top = $('.backtotop');
$(window).scroll(function() {
($(this).scrollTop() > offset) ? $back_to_top.addClass('is-visible'): $back_to_top.removeClass('is-visible fade-out');
if ($(this).scrollTop() > offset_opacity) {
$back_to_top.addClass('fade-out');
}
});
$back_to_top.on('click', function(event) {
event.preventDefault();
$('body,html').animate({
scrollTop: 0,
}, scroll_top_duration);
});
});
So you would change event listener assignments like the following:
$('.search').click(function(e) {
$(".search-overlay").addClass("visible");
e.preventDefault();
});
...to use the corresponding on method instead, passing the event name as an argument:
$('.search').on("click", function(e) {
$(".search-overlay").addClass("visible");
e.preventDefault();
});
Event delegation is avoiding adding several event listeners to specific nodes and instead adding a single event listener to a common parent element, which then looks to see which child element was clicked on.
There's a good article here:
https://www.google.co.uk/amp/s/davidwalsh.name/event-delegate/amp

Modify url based on a click event

I have a series of divs that when clicked it slides up basically a modal. The modal has a data-attribute that appears in the url. The issue I'm having is when I close the modal, the url still has the data-attribute hash, it doesn't revert back and I need it to.
This is the js:
$('[data-agent]').click(function() {
var element = $(this);
var target = element.data('agent');
$('body').addClass('agentLoaded');
$('[data-agent-target]').not('[data-agent-target="'+target+'"]').removeClass('active');
$('[data-agent-target="'+target+'"]').addClass('active');
window.location.hash = 'agent='+target;
return false;
});
if(document.location.hash){
var hash = document.location.hash.split('#')[1];
hash = hash.replace('agent=', '');
if(hash && $('[data-agent-target="'+hash+'"]').length) {
$('[data-agent="'+hash+'"]').trigger('click');
}
}
$('.close').click(function() {
$('[data-agent-target]').removeClass('active');
$('body').removeClass('agentLoaded');
return false;
});
[edit] Please see the question in the code
$('[data-agent]').click(function() {
var element = $(this);
var target = element.data('agent');
$('body').addClass('agentLoaded');
$('[data-agent-target]').not('[data-agent-target="'+target+'"]').removeClass('active');
$('[data-agent-target="'+target+'"]').addClass('active');
window.location.hash = 'agent='+target;
return false;
});
if(document.location.hash){ /* What is this for ? */
var hash = document.location.hash.split('#')[1];
hash = hash.replace('agent=', '');
if(hash && $('[data-agent-target="'+hash+'"]').length) {
$('[data-agent="'+hash+'"]').trigger('click');
}
}
$('.close').click(function() {
$('[data-agent-target]').removeClass('active');
$('body').removeClass('agentLoaded');
return false;
});

Stop continuous jQuery each() function on click and add active class

I have a jQuery each() function that loops through a set of three divs adding active to the items within the divs. I'm able to stop the loop on click for my function, but I'm having a hard time making it so that when you click on one of the items of a div, the other items that have the same class stays active. I know I can do it with if statements, but I'm having a hard time figuring it out.
HTML:
<div class="list-items loop-set">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
<div class="list-items loop-set">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
<div class="list-items loop-set">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
my function:
function doLoop() {
var $one = $('.one');
var $two = $('.two');
var $three = $('.three');
var interval = setInterval(function () {
$('.loop-set').each(function () {
var $set = $(this);
var $cur = $set.find('.active').removeClass('active');
var $next = $cur.next().length ? $cur.next() : $set.children().eq(0);
$next.addClass('active');
});
}, 1000);
$('.loop-set').on('click', '> *', function () {
var $this = $(this);
$('.loop-set .active').removeClass('active');
if ($this == $one) {
$one.addClass('active');
} else if ($this == $two) {
$two.addClass('active');
} else if ($this == $three) {
$three.addClass('active');
}
clearInterval(interval);
});;
}
doLoop()
I included my code on this fiddle. Any help/advice would be greatly appreciated!
Try
$('.loop-set').on('click', '> *', function () {
var $this = $(this);
$('.loop-set .active').removeClass('active');
$('.loop-set .'+this.className).addClass('active');
clearInterval(interval);
});
Demo: Fiddle
What about this more simplier code: http://jqversion.com/#!/ndZt3Zz/1
Is this the behaviour you want?
$('.loop-set').change(function () {
var $set = $(this);
var $cur = $set.find('.active').removeClass('active');
var $next = $cur.next().length ? $cur.next() : $set.children().eq(0);
$next.addClass('active');
});
var interval = setInterval(function(){
$('.loop-set').trigger('change');
}, 1000);
$('.loop-set > div').click(function(){
clearInterval(interval);
$('.loop-set > div').removeClass('active');
$('.' + $(this).attr('class')).addClass('active');
});
What about changing the onClick to something like this:
$('.loop-set').on('click', function () {
var $this = $(this);
$('.loop-set.active').removeClass('active');
$this.addClass("active");
clearInterval(interval);
});
What it does is it adds active class to loop-set making all of its children bolded. When you click another group - the highlight changes as well.
Here is the updated jsfiddle: http://jsfiddle.net/sL95U/5/. Hope it helps.

Transition between html pages using jquery to load a div?

I am trying to use jQuery to create a stylish transition between HTML pages.
however, I just need to fade in and fade out the content of the html pages.
for example:
I have two pages 1.html and 2.html
they both have a DIV called #content
I need to only fadein and fade out the div content instead of the entire html page.
I am using the code bellow:
<script type="text/javascript">
var speed = 'slow';
$('html, body').hide();
$(document).ready(function() {
$('html, body').fadeIn(speed, function() {
$('a[href], button[href]').click(function(event) {
var url = $(this).attr('href');
if (url.indexOf('#') == 0 || url.indexOf('javascript:') == 0) return;
event.preventDefault();
$('html, body').slideToggle(speed, function() {
window.location = url;
});
});
});
});
</script>
I've tried it like this as well and it didn't do anything:
<script type="text/javascript">
var speed = 'slow';
$('html, body').hide();
$(document).ready(function() {
$('html, body #content').fadeIn(speed, function() {
$('a[href], button[href]').click(function(event) {
var url = $(this).attr('href');
if (url.indexOf('#') == 0 || url.indexOf('javascript:') == 0) return;
event.preventDefault();
$('html, body').slideToggle(speed, function() {
window.location = url;
});
});
});
});
</script>
is this possible?
Thanks
Try this code
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('a[href], button[href]').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
Click Function
$('a[href], button[href]').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
Refer this fiddle
http://jsfiddle.net/fBrYp/2/

Get index of anchor/hash

I'm killing my self here.
When I type in index.html#about (or favorite it and open it) i want to get the index() of this, and insert it in the below script as "slideNumber".
Markup
<div id="slideshow">
<div id="frontpage">
<div id="About">
<div id="Contact">
</div>
jQuery
$(window).bind('hashchange', function () { //detect hash change
var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
$('.slideshow').cycle(slideNumber); //Slideshow-number
});
"#about" would be 2 and "#contact" would be 3 and so on.
How do I do this??
Something simple like this should work on the page load:
if(window.location.hash != undefined) {
var slideNumber = $(window.location.hash).index() + 1;
}
If you're navigating through the page, you can do your bind and do the index() call inside so that when the hash changes, it'll update:
$(window).bind('hashchange', function () { //detect hash change
var slideNumber = $(window.location.hash).index(); //slideNumber
$('.slideshow').cycle(slideNumber); //Slideshow-number
});
Give this a try
var slideNumber = $("div#" + window.location.hash.slice(1)).prevAll().length
slides = {frontpage: 1, about: 2, contact: 3};
$('.slideshow').cycle(slides[hash]);
To make it dynamic you could use something like this, I guess:
$('#slideshow>div').each(function(i) {
if(this.id == hash) {
$('.slideshow').cycle(i);
}
}
or
$('.slideshow').cycle($('#slideshow>div').index(hash) + 1);

Categories

Resources