I've added a javascript element I found in a guide. It is as follows
$(document).ready(function ()
{
$('.dropdownbutton').click(function ()
{
$.post("send.php", $(".mycontactform").serialize(), function (data)
{
});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
});
The existing javascript was
function toggleDisplayWait(divId, imgId, durationmSec) {
if(!$(divId).visible()) {
move = Effect.BlindDown;
newImage = "./img/minus.png";
}
else {
move = Effect.BlindUp;
newImage = "./img/plus.png";
}
move(divId, {duration: durationmSec / 1000.0 });
setTimeout(function() { $(imgId).src = newImage; }, durationmSec)
}
function BDEffect(divId, imgId)
{
/* new Effect.BlindDown(element, {duration:3});
}*/
if(!$(divId).visible())
{
move = Effect.BlindDown;
newImage = "./img/feedbacktab_open.png";
setTimeout(function() { $(imgId).src = newImage; }, 0)
}
else
{
move = Effect.BlindUp;
newImage = "./img/feedbacktab.png";
setTimeout(function() { $(imgId).src = newImage; }, 2)
}
move(divId, {duration:2});
/*setTimeout(function() { $(imgId).src = newImage; }, 0)*/
}
</script>
But neither the OLD code nor the NEW code works now.
Error console now reporting "$(divId).visible is not a function" when i try to use the old script
The old code looks like it's using the Prototype framework, and the new code is using jQuery.
When you use the two together, you need to use jQuery's noConflict() so that they don't both try to use the $ variable.
First, after including the jQuery library, add a script like this:
<script>
jQuery.noConflict()
</script>
Then modify your jQuery code to look like this:
jQuery(function ($) {
$('.dropdownbutton').click(function() {
$.post("send.php", $(".mycontactform").serialize(), function(data) {});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
With noConflict, everywhere you want to use jQuery, you must use the jQuery variable instead of $. However, you can still pass $ in as a local variable, and it will not conflict with Prototype.
Also, note that I changed your document.ready(function() { ... }) function into jQuery's shorthand version: jQuery(function() { ... }). The function will also get passed the jQuery object, which I name $ for convenience.
Related
I would like to know how to call the function below without refactoring from another js file.
$(document).ready(function() {
check();
function check () {
setTimeout(function(){
location.reload(true);
}, 10000);
}
});
I saw a question exist for this issue very old one but I cannot understand how to use the answer for my function.
StackOverflow answer from another question
I would like to see an example with my function and the proposed solution from the link.
My example which does not work correctly:
//= require rspec_helper
//= require background_index
//= require sinon
describe("Background Index, timeout after 10s", function() {
// Tweak for testing
var doc_ready = $.readyList[0]();
it ("Reload the location", function(){
clock = sinon.useFakeTimers();
var check = doc_ready.check();
var set_timeout = doc_ready.setTimeout();
/*var stub_check = sinon.stub(check, "check");
var stub_timeout = sinon.stub(timeout, "setTimeout");*/
timedOut = false;
setTimeout(function () {
timedOut = true;
}, 1000);
timedOut.should.be.false;
clock.tick(10010);
timedOut.should.be.true;
clock.restore();
});
});
This is re-written from the answer you pasted.
$(document).ready(check);
function check () {
setTimeout(function(){
location.reload(true);
}, 10000);
}
// In the test file
TestFile.prototype.testDocumentReadyContents = function () {
check();
}
A better way would be to include all the JS-files in your HTML with <script src="./path-to-file"> and then just call the functions in the order you want them to be called.
I created a small JQuery Plugin and I'm using thickbox for popups.
I don't know where it came from but I have a "0" appended to the end of the body element.
I suspect that one of those outputs a success indicator maybe?
Is anyone familiar with this behavior?
Edit:
PHP
add_action('wp_ajax_product_picker', 'popup_content');
function popup_content() {
iframe_header();
echo 'aaa';
iframe_footer();
}
JS
var currentPicker = {};
(function ($) {
$.fn.pick_product = function (options) {
var settings = $.extend({
callback: function(){}
}, options);
this.on('click',function () {
var url = product_picker.ajax_url + "?action=product_picker&TB_iframe=true&width=600&height=550";
tb_show("My Caption", url);
});
return this;
};
}(jQuery));
jQuery(function ($) {
$('#test-product-picker').pick_product({
callback: function (variation_id, size) {
alert('aaa');
}
});
});
If you are using it on the front end of your site you have to use the
wp_ajax_nopriv_product_picker and also place die() after your function.
function popup_content() {
iframe_header();
echo 'aaa';
iframe_footer();
die();
}
I've got a file which needs to run on page load (randomise_colors.js), but also needs to be called by another file as part of a callback function (in infinite_scroll.js). The randomise_colors script just loops through a list of posts on the page and assigns each one a color from an array which is used on the front-end.
Infinite Scroll loads new posts in to the DOM on a button click, but because the randomise_colors.js file has already ran on page load, new content loaded is not affected by this so I need it to run again. I'm open to other suggestions if it sounds like I could be tackling the problem in a different way, I'm no JS expert.
Currently I'm getting Uncaught ReferenceError: randomise_colours is not defined referring this line of infinite_scroll.js:
randomise_colours.init();
I'm calling all files that need be loaded on document.ready in app.js
require(['base/randomise-colours', 'base/infinite-scroll'],
function(randomise_colours, infinite_scroll) {
var $ = jQuery;
$(document).ready(function() {
infinite_scroll.init();
randomise_colours.init();
});
}
);
This is infinite_scroll.js which initialises Infinite Scroll and features the callback. The callback function runs whenever new items are loaded in via AJAX using the Infinite Scroll jQuery plugin. I've put asterix around the area where I need to run the randomise_colors.init() function from randomise_colors.js.
define(['infinitescroll'], function() {
var $ = jQuery,
$loadMore = $('.load-more-posts a');
function addClasses() {
**randomise_colours.init();**
};
return {
init: function() {
if($loadMore.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.initInfiniteScroll();
},
initInfiniteScroll: function() {
$('.article-listing').infinitescroll({
navSelector : '.load-more-posts',
nextSelector : '.load-more-posts a',
itemSelector : '.standard-post'
}, function(newItems) {
addClasses();
});
//Unbind the standard scroll-load function
$(window).unbind('.infscr');
//Click handler to retrieve new posts
$loadMore.on('click', function() {
$('.article-listing').infinitescroll('retrieve');
return false;
});
}
};
});
And this is my randomise_colors.js file which runs fine on load, but needs to be re-called again after new content has loaded in.
define([], function() {
var $ = jQuery,
$colouredSlide = $('.image-overlay'),
colours = ['#e4cba3', '#867d75', '#e1ecb9', '#f5f08a'],
used = [];
function pickRandomColour() {
if(colours.length == 0) {
colours.push.apply(colours, used);
used = [];
}
var selected = colours[Math.floor(Math.random() * colours.length)];
var getSelectedIndex = colours.indexOf(selected);
colours.splice(getSelectedIndex, 1);
used.push(selected);
return selected;
};
return {
init: function() {
if($colouredSlide.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.randomiseColours();
},
randomiseColours: function() {
console.log('randomise');
$colouredSlide.each(function() {
var newColour = pickRandomColour();
$(this).css('background', newColour);
});
}
};
});
You would have to reference randomiseColours inside the infiniteScroll file. So you need to change your define function to the following:
define(['infinitescroll', 'randomise-colours'], function(infiniteScroll, randomise_colours)
Remember that when using require you need to reference all variables through the define function, otherwise they will not be recognised.
I have this javascript:
Modernizr.load([
{
test: Modernizr.canvas,
nope: ['/assets/js/excanvas.js'],
both: ['/assets/js/frank/pentool.js'],
complete : function () {
var cmo = new CutMeOut(settings);
}
}
]);
This loads in excanvas should canvas not be supported and when complete should fire the "complete" function. The CutMeOut class in pentool.js contains code that works with the canvas element. However, IE7 and IE8 are giving this error:
Object doesn't support property or method
If I just load excanvas normally the site works. So, how do I get var cmo = new CutMeOut(settings); to run after excanvas has pollyfilled the problem?
Thanks.
Seems to be work:
Modernizr.load([
{
load: '/assets/js/frank/pentool.js',
complete: function() {
if (!document.createElement('canvas').getContext) {
Modernizr.load('/assets/js/excanvas.js');
} else {
var cmo = new CutMeOut(settings);
}
}
},
{
complete: function() {
if (!document.createElement('canvas').getContext) {
window.addEvent('load', function() {
var cmo = new CutMeOut(settings);
});
}
}
}
]);
If I have an element on the page like this ...
<span data-function="DoSomething">Click</span>
... and i put this in my page header ...
$(document).ready(function()
{
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fName);
});
});
... what goes in place of the comment produce the desired effect of executing the function called "DoSomething".
Note:
I no the code above wont work, my question is how to make this work (translate 'DoSomething' in to DoSomething();)
Any ideas guys?
The functions should be available. Try putting them in an Object, like this:
$(document).ready(function()
{
var fns = {
DoSomething: function() {/* ... */},
DoAnotherthing: function() {/* ... */}
};
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fns[fName]);
});
});
Here's a jsfiddle, demonstrating a way to keep everything local to one namespace and assigning handlers based on the data attribute of elements.
Try calling function with window object -
$(document).ready(function() {
$('[data-function]').each(function() {
var fName = $(this).attr('data-function');
if (typeof (window[fName]) === "function") {
$(this).click(window[fName]);
}
});
}
You can use something like
$(this).click(window[fName]);
Where window would be replaced by the appropriate expression if the function DoSomething is not defined in the global scope.
Maybe a little bit clean way:
http://jsfiddle.net/whsPG/
var myfuncs = {
alert : function() {
alert("An Alert");
},
changeName: function(obj) {
$(obj).text('Other Text');
}
};
$('[data-function]').on('click', function()
{
value = $(this).data('function');
if (myfuncs.hasOwnProperty(value)) {
myfuncs[value](this);
}
});