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

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');
}
}
});

Related

Add Active Class when Scrolling and Clicking

I hope someone will be able to help me with my code, I want to add the active class when scrolling not just by clicking. How can I do that on my code. I'm not good at javascript or jquery. Thank you so much
jQuery(document).ready(function($) {
//you can now use $ as your jQuery object.
$('div p').click(function() {
$(this).addClass('active').siblings().removeClass('active');
})
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="article-links">
<p class="active">US Dollar rates and purchasing power are in all time low</p>
<p>Huge institutional interest</p>
<p>Strong fundamental growth and usage on overall blockchain ecosystem</p>
</div>
Your code works. It might be more obvious with a noticeable change. I've styled the active class to increase font-size.
jQuery(document).ready(function($) {
//you can now use $ as your jQuery object.
$('div p').click(function() {
$(this).addClass('active').siblings().removeClass('active');
})
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
});
.active {
font-size: 24px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="article-links">
<p class="active">US Dollar rates and purchasing power are in all time low</p>
<p>Huge institutional interest</p>
<p>Strong fundamental growth and usage on overall blockchain ecosystem</p>
</div>

Track clicks on different iframes with JavaScript

I am trying to track clicks on iframes on my site. So far this code is working and is triggered every time a click happens on an iframe.
var monitor = setInterval(function() {
var elem = document.activeElement;
if(elem && elem.tagName == 'IFRAME'){
alert('click on iframe');
clearInterval(monitor);
}
}, 500);
Now what I would like to do is to trigger different actions based on which iframe is clicked. Since I don't have control over classes or id's that the iframes might have I need to rely on the parent div's which are under my control, so I'm trying something like this which is currently not working.
var monitor = setInterval(function() {
var elem = document.activeElement;
if(elem && elem.tagName == 'IFRAME'){
if ($elem.parents('.ad_left').length) {
alert('this is an ad left iframe');
}
else if ($elem.parents('#youtube').length) {
alert('this is a youtube iframe');
}
else () {
alert('click on different iframe');
}
clearInterval(monitor);
}, 500);
Is this not possible or amd I missing something?
I managed to get it working, this is the code I used to check fi any ancestor of the iframe contains a particular class and performing different actions based on that:
var monitor = setInterval(function() {
var elem = document.activeElement;
if(elem && elem.tagName == 'IFRAME'){
if (elem.closest('.class_one') !== null) {
alert('this iframe has a parent with class class_one');
}
else if (elem.closest('.class_two') !== null) {
alert('this iframe has a parent with class class_two');
}
else if (elem.closest('.class_three') !== null) {
alert('this iframe has a parent with class class_three');
}
clearInterval(monitor);
}
}, 500);

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

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.

Conflicting "back to top" scripts - how to fix?

I'm using 2 scripts found on the internet, one for a smooth scroll to a DIV at the bottom of the page, and one for a smooth scroll "Back to top". The issue is that there's a conflict between both and therefore the "back to top" one doesn't work (no back to top on click). Used independently they both work perfectly.
How could I "merge" them both into one single script? (and keep the fade-in fade-out effect of the back to top script) See http://jsfiddle.net/GjsVq/1/
Many thanks
$(document).ready(function() {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
$(document).ready(function() {
var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
})
});
$('a[href^="#"]').on(... is selecting both <a> elements. One approach is to either rewrite this selector to match only the <a> elements that should force a scroll to the bottom (maybe use a CSS class for this?)
An alternative, quick-and-dirty fix would be to reset the event handlers on the "back-to-top" element before attaching its own click handler: jQuery('.back-to-top').off().click(...
I normally just use one smooth scroll function and then set my "go to top" button with a href="#idOfHighestElementOnPage". This is the smooth scroll function (which may include something helpful if you don't want to go the same route I went):
$(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();
}
}

Javascript loads offline but not in drupal

I am trying to incorporate the Javascript and load it into drupal. The problem is executing it. I know it is a simple problem but my knowledge does not extend beyond adding the javascript to the drupal page. When I load it in dreamweaver offline it loads perfectly and works.
$(document).ready(function(){
//function for contact form dropdown
function contact() {
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
$("#backgroundPopup").css({"opacity": "0.7"});
$("#backgroundPopup").fadeIn("slow");
I know the problem is with the first three lines. Cause when I load it in chrome it tells me the problem is on line 1.
I know it is something with drupal, I don't know if javascript needs to be loaded differently in Drupal.
The error that is given is: UnCaught Type Error : Property $ of Object Window is not a function.
Assistance for ignorance please....
$(document).ready(function(){
//function for contact form dropdown
function contact() {
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
$("#backgroundPopup").css({"opacity": "0.7"});
$("#backgroundPopup").fadeIn("slow");
}
else{
$("#contactForm").slideUp("slow");
$("#backgroundPopup").fadeOut("slow");
}
}
//run contact form when any contact link is clicked
$(".contact").click(function(){contact()});
//animation for same page links #
$('a[href*=#]').each(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($(this.hash).length) {
$(this).click(function(event) {
var targetOffset = $(this.hash).offset().top;
var target = this.hash;
event.preventDefault();
$('html, body').animate({scrollTop: targetOffset}, 500);
return false;
});
}
}
});
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "")){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
//only need force for IE6
$("#backgroundPopup").css({
"height": document.documentElement.clientHeight
});
});
$ isn't an alias for jQuery by default in Drupal 7, you need to pass it in like so:
(function($) {
// Your code here
})(jQuery);
See Managing JavaScript in Drupal 7 for more info.

Categories

Resources