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.
Related
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.
I am trying to use one of the IE9 IE8 placeholder solutions, but i have an error showing in IE9 test setup with the code. The solution i am using is clearly working for many people according to the comments and updates in github, but I have a fundamental problem getting the code recognised.
I have this line in my page header, which should allow me to use jquery. Indeed i am running other jquery functions and they seem to be working:
<!-- Javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Also in the head i have this (again all the other functions in my myjs.js are showing in developer tools and are available as required):
<!-- my java code link -->
<script src="/js/myjs.js"></script>
The function that i am using for the placeholder solution is this one:
placeholderSupport = ("placeholder" in document.createElement("input"));
if (!placeholderSupport) {
//This browser does not support the placeholder attribute
//use javascript instead
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() === '' || input.val() === input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
}
})
});
}
The error that i am getting from IE9 developer tools is this:
Invalid App Id: Must be a number or numeric string representing the application id.
The error is showing on the line of code that looks like this, specifically the dollar sign:
$('[placeholder]').focus(function() {
From my reading I thought that the $ start was a function of the jquery library, which i beleive to be present and working, but i am obviously missing a trick. Can anybody help please. Thanks for any guidance.
Try this code, It works IE8+
UPDATED: to match all inputs and textarea
// This adds 'placeholder' to the items listed in the jQuery .support object.
jQuery(function () {
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$('input,textarea').focus(function () {
if ($(this).attr('placeholder') !== '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('has-placeholder');
}
}).blur(function () {
if ($(this).attr('placeholder') !== '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('has-placeholder');
}
});
$('input,textarea').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$('input.has-placeholder,textarea.has-placeholder').val('');
});
}
});
Plus CSS
.has-placeholder {
color:#777 /*whatever you like*/
}
Here is the final code using Dippas' answer with the extras to cover textareas and inputs that have type='tel' rather than type='text'. This seems to cover everything on my form, but there might be other input types that need adding at other times. I'm sure that somebody who knows what they are doing can trim this down by sorting out some of the duplicate code.
// This adds 'placeholder' to the items listed in the jQuery .support object.
jQuery(function() {
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function() {
if (!$.support.placeholder) {
var active = document.activeElement;
$('textarea').focus(function() {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('has-placeholder');
}
}).blur(function() {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('has-placeholder');
}
});
$('textarea').blur();
$(active).focus();
$('form:eq(0)').submit(function() {
$('textarea.has-placeholder').val('');
});
$('input').focus(function() {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('has-placeholder');
}
}).blur(function() {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('has-placeholder');
}
});
$('input').blur();
$(active).focus();
$('form:eq(0)').submit(function() {
$('input.has-placeholder').val('');
});
}
});
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');
}
}
});
How do you make i.e. read the value of attribute included to an element by query?
Everything works fine with Safari, Chrome, Firefox.
The value of "type" below returns undefined only with i.e.
$(document).ready(function() {
//edit post
$(function()
{
$("input[value='Edit']").click(function()
{
$("input#password").attr("rel", "edit");
});
return false;
});
//----end
//delete post
$(function()
{
$("input[value='Delete']").click(function()
{
$("input#password").attr("rel", "delete");
});
return false;
});
//----end
});
$( document ).on( "keypress", ".enter-pw", function(e){
var code = e.keyCode || e.which;
if(code == 13) {
var password = $("input#password").val();
var type = $(this).attr("rel");
if(password == ""){
return false
}
if(type=="delete"){
//do stuffs
}
if(type=="edit"){
//do stuffs
}
return false;
}
});
Problem solved guys.
It was caused by the placeholder plugin which activated only with i.e. .
Why do you use $(this) to get entry_id and $("input#password") to get password ? Can you try to use $("input#password") both time ?
I'm using a JS to activate the active link within a menu.
Problem is, my CMS places a forward slash before menu items. As soon as it does this, the JS no longer works. If I remove the slash, it works again.
Any ideas how I get it to work with and without the forward slash?
Here's a page I'm testing it on: http://www.sunseedor...k/products1.php
JS is:
$(function(){
var $page = jQuery.url.attr("file");
$('ul.top-nav li a').each(function(){
var $href = $(this).attr('href');
if ( ($href == $page) || ($href == '') ) {
$(this).addClass('on');
} else {
$(this).removeClass('on');
}
});
});
you might want to try this :
$(function(){
var currUrl = window.location.href;
if(currUrl.substr(-1) == "/")
jQuery.url.setUrl(currUrl.substr(0,currUrl.length-1));
var $page = jQuery.url.attr("file"); /* this comes as null
if the URL has ending slash*/
$('ul.top-nav li a').each(function(){
var $href = $(this).attr('href');
if ( ($href == $page) || ($href == '') ) { $(this).addClass('on'); }
else {
$(this).removeClass('on');
} });
});