JS is included, but won't fire on load? - javascript

I have a js script that is supposed to fix my side menu on scroll. It shows it being included in the view source and if I copy/paste my code into console to auto-fire it, it works perfectly.
How can I figure out why it won't fire on load? No errors are thrown either. The file in question has 2 functions, the first is to fix the menu to to top and the second deals with changing content out by checking checkboxes.
Here is my script:
// FIX SIDE BAR AFTER SCROLL
$(window).load(function() {
console.log('test');
$("a[href*=#]:not([href=#])").click(function() {
if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
var o = $(this.hash);
if (o = o.length ? o : $("[name=" + this.hash.slice(1) + "]"), o.length) return $("html,body").animate({
scrollTop: o.offset().top
}, 900), !1
}
});
console.log('test2');
$(window).load(function() {
var o = $(".sticky").offset().top,
t = function() {
var t = $(window).scrollTop();
t > o ? $(".sticky").addClass("stuck") : $(".sticky").removeClass("stuck")
};
t(), $(window).scroll(function() {
t()
});
console.log('test3');
});
//RADIO BUTTON CONTENT CHANGER
$(function(){
$('input[name="pricing-radios"]').on('change', function(){
if ($(this).val()=='pricing1') {
//change to "show update"
$(".pricing-engage-chng").text("179");
$(".pricing-engage-chng-additional").text(".01");
$(".pricing-crm-chng").text("214");
$(".pricing-crm-chng-additional").text(".01");
$(".upgrade-price").text(".0025");
} else if ($(this).val()=='pricing2') {
$(".pricing-engage-chng").text("699");
$(".pricing-engage-chng-additional").text(".005");
$(".pricing-crm-chng").text("714");
$(".pricing-crm-chng-additional").text(".006");
$(".upgrade-price").text(".0015");
} else if ($(this).val()=='pricing3') {
$(".pricing-engage-chng").text("3,499");
$(".pricing-engage-chng-additional").text(".0025");
$(".pricing-crm-chng").text("3,514");
$(".pricing-crm-chng-additional").text(".00325");
$(".upgrade-price").text(".00075");
}
});
});
});
My code seems to work in my JSFiddle and as I said, copy and pasting my code into my console will fire my command and yield the desired result.
You can see the live page here as well.
Thanks for the help!

Alright so I figured this out:
The framework we use has an auto-minify function in it. So when I pulled the old code through, this part is technically minified. So my vars were returning unknown elements.
$(window).load(function() {
var o = $(".sticky").offset().top,
t = function() {
var t = $(window).scrollTop();
t > o ? $(".sticky").addClass("stuck") : $(".sticky").removeClass("stuck")
};
t(), $(window).scroll(function() {
t()
});
I ended up rewriting a function to add the class and simplified it a little more and came up with this:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
//if less than or = to 350 add class
if (scroll >= 350) {
$(".sticky").addClass("stuck");
// else remove class
} else {
$(".sticky").removeClass("stuck");
}
});
Now this one gets minified, but everything is predefined and is readable.

Related

JS code not running correctly, but works on console

I'm trying to change the src of an image. I'm able to change it on console but I can't put it to work on my javascript file. The code I ran is the same as the code on my file.
Here is the excerpt of my code where it's giving me problems:
$(document).ready(function(){
$(document).on("click", ".grid-zonaAzul div img", function(event){
if ($(event.target).attr("src") != "imagens/reservaCadeiras/cadeiraIndisponivel1.png") {
if ($(event.target).attr("src") == "imagens/reservaCadeiras/cadeiraSelecionadaChapeu1.png") {
var parentClass = $(event.target).parent().attr("class");
var classDots = "." + parentClass.split(" ").join(".");
console.log(classDots);
document.querySelector(classDots + " > img");
// document.querySelector(classDots + " > img").setAttribute("src", "imagens/reservaCadeiras/cadeira1.png");
};
};
});
});
And on HTML there's something like this:
<div class="grid-zonaAzul">
<div class="linha1a coluna1a"><img src="imagens/reservaCadeiras/cadeira1.png"></div>
</div>
The var parentClass is giving me the class linha1a coluna1a, which is correct. But because I need it with dots, I'm running the line var classDots = "." + parentClass.split(" ").join("."); to turn the string to .linha1a.coluna1a. Also, the console.log
So basically I'm trying to get the only image inside de class .linha1a.coluna1a. The problem starts here, because the commented line isn't doing anything but if I run document.querySelector(".linha1a.coluna1a > img").setAttribute("src", "imagens/reservaCadeiras/cadeira1.png"), it works on console.
Edit:
I'm sorry, I didn't explained somethings.
I have an image, when I click on it it changes to other image. This is working correctly. The code I posted was running when I clicked on the image again to replace the second image to the first image it was showing.
Essentially, the first click changes the src to imagens/reservaCadeiras/cadeiraSelecionada1.png and the second click changes to imagens/reservaCadeiras/cadeira1.png.
If your intention is to change the Image1 to Image2 and from Image2 to Image3 on each click, then your condition blocks doesn't satisfy what you intend to achieve.
It should be something like this...
$(document).ready(function(){
$(document).on("click", ".grid-zonaAzul div img", function(event){
if ($(event.target).attr("src") == "Image1.png") {
$(event.target).attr("src","Image2.png");
};
else if ($(event.target).attr("src") == "Image2.png") {
$(event.target).attr("src","Image3.png");
};
else if ($(event.target).attr("src") == "Image3.png") {
$(event.target).attr("src","Image1.png");
};
});
});
I've found the problem, it was a stupid error. I never thought the problem was on something else other the first if. My code was this:
$(document).ready(function(){
$(document).on("click", ".grid-zonaAzul div img", function(event){
if ($(event.target).attr("src") != "imagens/reservaCadeiras/cadeiraIndisponivel1.png") {
if ($(event.target).attr("src") == "imagens/reservaCadeiras/cadeiraSelecionada1.png") {
$(event.target).attr("src","imagens/reservaCadeiras/cadeira1.png");
}
if ($(event.target).attr("src") == "imagens/reservaCadeiras/cadeiraSelecionadaChapeu1.png") {
var parentClass = $(event.target).parent().attr("class");
var classs = "." + parentClass.split(" ").join(".");
console.log(classs);
document.querySelector(classs + " > img")
// .setAttribute("src", "imagens/reservaCadeiras/cadeira1.png");
// $(event.target).attr("src","imagens/reservaCadeiras/cadeira1.png");
}
if ($(".w3-select").val() == "sim") {
$(event.target).attr("src","imagens/reservaCadeiras/cadeiraSelecionadaChapeu1.png");
}
else {
$(event.target).attr("src","imagens/reservaCadeiras/cadeiraSelecionada1.png");
}
}
});
});
The problem was it was entering on the second if and then on the third if. This was easily corrected by using else if.
Solution:
$(document).ready(function(){
$(document).on("click", ".grid-zonaAzul div img", function(event){
if ($(event.target).attr("src") != "imagens/reservaCadeiras/cadeiraIndisponivel1.png") {
if ($(event.target).attr("src") == "imagens/reservaCadeiras/cadeiraSelecionada1.png") {
$(event.target).attr("src","imagens/reservaCadeiras/cadeira1.png");
}
else if ($(event.target).attr("src") == "imagens/reservaCadeiras/cadeiraSelecionadaChapeu1.png") {
$(event.target).attr("src","imagens/reservaCadeiras/cadeira1.png");
}
else if ($(".w3-select").val() == "sim") {
$(event.target).attr("src","imagens/reservaCadeiras/cadeiraSelecionadaChapeu1.png");
}
else {
$(event.target).attr("src","imagens/reservaCadeiras/cadeiraSelecionada1.png");
}
}
});
});

$(this).hide() hides containers it shouldn't

I have this little piece of code that filters through a list of results and hides the divs that don't match. I am writing this for a PhoneGap iOS application. It works fine on Android, but on iOS for some reason it hides the entire search field as well after typing a few characters, not just the results.
Any idea why? I've stripped it down to almost only the HTML code and jQuery and it's still happening. I tried commenting out the $(this).hide(); part and it stops hiding the search field, so I assume somehow that's the culprit, but I can't figure out why or how to fix this. Been at it for 10 hours straight. Any ideas? Maybe I can target the results some other way?
$('#box_search').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#listing-results > .listing_container').show();
} else {
$('#listing-results > .listing_container').each(function() {
var text = ($(this).find('.listing_results_text_name').text() + $(this).find('.listing_results_text_name').data("alt")).toLowerCase();
if (text.indexOf(valThis) >= 0) {
$(this).show();
} else {
$(this).hide();
}
});
};
});
obviously I cant see the html but sometimes it helps to clean the code and just change the logic slightly
var box_search = function(e){
var myIndex = $(this).val();
val = (!myIndex || myIndex==='')?false:myIndex;
if(!myIndex){
$('#listing-results > .listing_container').show();
return;
}
//
$('#listing-results > .listing_container').each(function() {
var text = $(this).find('.listing_results_text_name').text() +
$(this).find('.listing_results_text_name').data("alt")
text = (!text || text==='')?false:text;
text = text.toLowerCase();
if(text.indexOf(myIndex.toLowerCase()) >= 0){
$(this).show();
return;
}
$(this).hide();
});
} //end of function
$('.box_search').keyup(box_search);

Fancybox opening issue - works on JSFiddle but not in live environment

I'm trying to get a fancy box popup opening when the user click on "CONTACT" in the navigation menu. It works on JSFiddle, see http://jsfiddle.net/88X6D/1/ but for some reason it doesn't work in live environment, see http://goo.gl/lkfxeO (nothing happens when clicking on "contact" in the menu)
I initially thought there was a conflict between the "smooth scrolling" script and the "contact form" script but since it works on JSfiddle, the issue must be somewhere else. (also fancybox JS files and jquery are correctly called).
Thanks for your help
HTML
<li> Contact
</li>
SCRIPTS (located in this file: js/scripts.js)
//==============
//! Smooth scrolling
//==============
$(function () {
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 100
}, 'normal');
return false;
}
}
});
})
window.onscroll = scrollFunction;
function scrollFunction() {
var doc = document.documentElement, body = document.body;
var top = (doc && doc.scrollTop || body && body.scrollTop || 0);
if (top > 200) {
$('.back-to-top').fadeIn();
}
else {
$('.back-to-top').fadeOut();
}
}
//==============
//! Contact form
//==============
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var nameval = $("#name").val();
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(nameval < 2) {
//name must be at least 2 characters
$("#name").addClass("error");
}
else if(nameval >= 2){
$("#name").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: '../sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your message has been sent, thank you.</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
The problem is in your click handlers. Your 'contact' link ends up with two handlers:
One for scrolling (set up in your $('a[href*=#]:not([href=#])').click() call)
One for Fancybox (implicitly added by the call to $('.modalbox').fancybox()).
The scrolling click handler ends with return false. This stops all later click handlers running. Thus your scrolling click handler runs, but Fancybox's click handler doesn't - the scrolling click handler told the browser not to.
The scrolling click handler should have an ev.preventDefault() call instead. ev.preventDefault() stops the browser carrying out the "default" action (in this case, trying to follow the link), but doesn't prevent later click handlers running.
Here's an updated scroll handler that should get your Fancybox working:
$('a[href*=#]:not([href=#])').click(function (ev) { // Added 'ev' parameter
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
ev.preventDefault(); // We're animating this, so don't let the browser try to navigate to this URL
$('html,body').animate({
scrollTop: target.offset().top - 100
}, 'normal');
}
}
});

jquery cycle slideshow, with keycode navigation

I'm using a slideshow on my website using jquery Cycle 1.
I navigate into my slideshow with #next function. when clicking on my last slide of my slideshow it redirect me to another page (var random_next_url_enfant).
I would like to add the spacebar and the right arrow key to navigation inside my slideshow.
when I add this Js code it works, but on the last slide it starts the slideshow again instead of redirecting me to the next page.
$(document.documentElement).keyup(function (e) {
if (e.keyCode == 39)
{
$('#slider_projets').cycle('next');
}
});
here is my full code using the mouse click. on the last slide, it redirects me to another page, it works perfectly. but I would like to get the same with the spacebar and the right arrow :
$('#slider_projets').cycle({
speed: 600, //temps d'animation
timeout: 0, //fréquence
fx: 'scrollLeft',
//compteur//
pager: "#nav",
after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
$('#counter_1').text((options.currSlide + 1) + ' / ' + (options.slideCount));
slideIndex = options.currSlide;
nextIndex = slideIndex + 1;
prevIndex = slideIndex - 1;
if (slideIndex == options.slideCount - 1) {
/*nextIndex = 0;*/
var random_next_url_enfant = $("#random_next_url_enfant").val();
$('#next').on("click", function(e){
e.preventDefault();
window.location = random_next_url_enfant;
});
}
if (slideIndex === 0) {
prevIndex = options.slideCount - 1;
}
}
});
I think i'm missing something but I can't find what !
here is a jsfiddle :
http://jsfiddle.net/8HsdG/
thanks a lot for your help,
You need access to your slider options outside of your slider, the reason you are not getting to the url is because there is no listener telling it to go there, only the click event.
Here is a jsfiddle that will get you very close, it has everything you need, you just have to fill in the blanks.
http://jsfiddle.net/kkemple/8HsdG/1/
I wrapped your code in an anonymous function so I could declare some scoped variables
(function () {
var slideIndex, slideCount;
// all of your code is here
})();
I then added a before call on your slider:
before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
slideCount = options.slideCount;
},
then added the following code to your key events:
if ( slideIndex == slideCount ) {
//redirect to random url
e.preventDefault;
}
#kkemple, I've resolved the problem... I just had to change :
$(document.documentElement).keyup(function (e) {
if (e.keyCode == 32)
{
$('#slider_projets').cycle('next');
}
});
by
$(document.documentElement).keyup(function (e) {
if (e.keyCode == 32)
{
$("#next").trigger("click");
}
});
and it works perfectly ! anyway thanks for your help !

Why is smooth scrolling.js throwing a "$target.offset(...) is undefined" error?

I have a bit of javascript that smooth scrolls to any clicked #anchor-id (adaptation of this). For certain pages it throws a $target.offset(...) is undefined error, and stops working, and I don't understand why.
I have done some testing and it seems to be correlating to the length of the page, as far as I can tell. Keeping all variables the same, only varying the amount of content, the bug occured (on the exact same page).
The weird thing is that I haven't been able to reproduce this effect on jsfiddle, it works fine over there, for every length. Does anyone know how to troubleshoot this bug? What could be the cause of it?
This is the javascript I'm using (I link to it at the bottom of every page, right before the </body> tag and immediately after loading jquery 1.10.2):
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// commented line below because it adds a hash to the url and a history item
// location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
This happens when the hash target does not exist. In HTML5 a valid hash target can only be written with an id.
So this will not work:
<a name="#hash">Hash</a>
But this will:
<a id="#hash">Hash</a>
Since using name="" isn't valid HTML5, #hash does not exist on the page so when you try to reference it with this:
var $target = $(this.hash)
It returns undefined. Even links with valid hash targets won't smooth scroll if they are included after invalid ones because of this.
I know it is an old question, but i had this problem recently and the suggested solution did not help. The used script for smooth scrolling has an error. It only checks if the link links to an anchor. But not if the anchor target actually exists on the current page. So the line
if (target) {
should be
if ($target.length > 0) {

Categories

Resources