I am working on MVC application and I have jQuery plugin, calculating width and height of page and I am calling this from document.ready function. I am getting following error
ReferenceError: getPreventDefault is not defined MyCustomScript:1:115
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5389:0
no element found
my plugin
(function($) {
$.fn.adjustOuterStripLayout = function () {
alert("strip");
$(window).bind('load resize', function () {
var viewport_height = $(window).height();
var viewport_width = $(window).width();
var webPage_containerWidth = $('.container').width();
alert("viewport_width " + viewport_width + "container " + webPage_containerWidth);
});
};
})(jQuery);
main function
$(document).ready(function () {
alert("hello");
$(this).adjustOuterStripLayout();
});
sometime it alert and sometime it not. I have also clear browser cashed and testing this on firefox and jquery version 1.10.2
Can you try the same in 'window.onload' event instead of in 'documen.ready' ?
As, you are trying to refer the window object to get height & width. Unless its not loaded you wont get that value.
Try using code like:
$(window).load(function () {
$(this).adjustOuterStripLayout();
});
Related
I have this Javascript function for hover items. İt has to work under 958px but its not working. so how can I control that.
But when I resize page up and down, JS stops working.
What's wrong with my function? I am unable to figure it out.
$(document).ready(() => {
if ($(window).width() >958){
$('#group-subscription .owl-item').on('mouseenter', function(){
$(this).nextAll().addClass('has-positive-translate')
$(this).prevAll().addClass('has-negative-translate')
}).on('mouseleave', function() {
removeHasClasses()
})
function removeHasClasses() {
$('#group-subscription .owl-item').removeClass('has-negative-translate has-positive-translate slider-hover-bigger')
}
}
})
Your code is not related to resizing event, it only one time execute when a page is loaded and it is ready, All in all, you should use resize event instead of the ready event.
$(window).on('resize', function(){
var winx = $(this);
if (winx.height() >= 958) {
/* use your code here */
}
});
I am working on a function that changes the source of an image tag to a background-image. This function should be really helpful for the way images will look in IE. I have tried debugging, but I get stuck on an object expected error. This happens on the second line:
if ( ! Modernizr.objectfit ) {
$('.wrapper__figure').each(function () {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container
.css('backgroundImage', 'url(' + imgUrl + ')');
}
});
}
The only way I can get that code to cause that error in IE is if jQuery's noConflict has been used, so $ isn't jQuery anymore (example: http://output.jsbin.com/bixijotala). If so, you probably want to use an IIFE to use a local $, passing in jQuery:
(function($) {
if ( ! Modernizr.objectfit ) {
$('.wrapper__figure').each(function () {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container
.css('backgroundImage', 'url(' + imgUrl + ')');
}
});
}
})(jQuery);
Or of course, you'd get this if you don't have jQuery loaded at all, in which case the answer is: Load jQuery, prior to running that code.
I'm using jquery 1.9.1 and I'm trying to develop a plugin. The problem is that the plugin isn't working. Here's the code:
;(function($) {
$.fn.single = function() {
return this.each(function(){
// Get the instance
var element = $(this);
// Resize the "data-target" divs
element.load(function(){
changeCSS(element);
});
// Bind the method to the resize window event
$(window).bind("resize", function(){
changeCSS(element);
});
});
};
// function to resize all the "data-target" divs
function changeCSS(element) {
// Grab the screen resolution
var windowWidth = $(window).width();
var windowHeight = $(window).height();
// Count how many targets the div has
var targetsSize = $("[data-target]").size();
// Resize the parent div
$(element).css({
"width" : windowWidth,
"height": windowHeight * targetsSize
});
// Resize all the targets div
$(element + "> div[data-target]").each(function(){
$(this).css({
"width" : windowWidth,
"height": windowHeight
});
});
}
})(jQuery);
And I'm calling it on the document like that:
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/single-0.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#single").single();
});
</script>
There's no problem in the console. What I'm doing wrong?
I'm assuming that it is because you are misusing the method .load. If you look at the jQuery docs, it is intended for:
.load() : Load data from the server and place the returned HTML
into the matched element.
http://api.jquery.com/load/
Remove the lines element.load(function ..., simply call your changeCSS function, you're already loading this extension on Document.Ready
return this.each(function () {
// ...
changeCSS(element); // <-- just run the function right away
// ... etc
});
Generally it is bad practice to call a function before it is declared. To get your plugin right, you will be better of starting structuring it correctly from the beginning. Besides that, as #mcpDESIGNS point out, you are using the .load method wrongly. Also, it would be useful if you explain what exactly it is you are trying to accomplice here.
To get a good start making jQuery plugins, try to look at the documentation at jQuery here or you can look at this tutorial.
This is the preferred structure:
(function($) {
// Declare your methods at the beginning of your plugin
var yourMethods = {
'methodOne' : function() {
},
'methodTwo' : function() {
}
};
$.fn.pluginName = function() {
return this.each(function() {
});
}
}(jQuery));
Instead of:
element.load(function(){
changeCSS(element);
});
I did:
changeCSS(element);
And... Instead of:
$(element + "> div[data-target]")
I did:
$(element).children('div[data-target]')
And now the plugin is being executed with no bugs or errors.
Thanks Guys!
I'm trying to access the selector of the jQuery object inside of the closure below so that I don't have to specify it and/or cache it. If I replace $(".the_lead") with $this, it won't perform it's action.
Invoking the plugin
$(".the_lead").scroll_lead({speedup: 400});
Block
var $this = $(this);
$(window).scroll(function() {
var window_height = $(window).height();
var document_height = $(document).height();
var hide_lead;
var scrollTop = $(window).scrollTop();
console.log($this);
if(!hide_lead){
if(scrollTop>(document_height/2)){
$(".the_lead").slideDown(options.speedup);
}else{
$(".the_lead").slideUp(500,function(){
$(".the_lead").hide();
});}
}
$('#hide_lead').click(function(e){
//$(".the_lead").parent().parents('div').hide();
hide_lead = true;
e.preventDefault();
});
});
Console Output for $(this):
[selector: ".the_lead", context: document, constructor: function, init: function, selector: ""…]
context: #document
length: 0
selector: ".the_lead"
__proto__: Object[0]
Notice the length: 0 output by the console. The window scroll event fires more or less every pixel the user moves. Without seeing more of your plugin's code I couldn't be sure, but I'd bet $this is correct only the first time the scroll event fires.
Additionally, caching it seems like you'd want to cache only one of the .the_lead elements, no? That's how your code reads. with $this = $(this); but then within the function you seem to want all elements with the class .the_lead. Try directly caching it like this instead. $this = $('.the_lead');
What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer?
And can you turn both scrollbars on/off?
jQuery has a built-in method for this:
$(window).resize(function () { /* do something */ });
For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:
function doSomething() {
alert("I'm done resizing for the moment");
};
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
});
$(window).bind('resize', function () {
alert('resize');
});
Here is the non-jQuery way of tapping into the resize event:
window.addEventListener('resize', function(event){
// do stuff here
});
It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.
Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:
function foo(){....};
window.onresize=foo;
Since you are open to jQuery, this plugin seems to do the trick.
Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):
// did not work in IE10
$(function() {
$(window).resize(CmsContent.adjustSize);
});
while this worked in both browsers:
// did work in IE10
$(function() {
$(window).bind('resize', function() {
CmsContent.adjustSize();
};
});
Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.
jQuery provides $(window).resize() function by default:
<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
$rightPanelData = $( '.rightPanelData' )
$leftPanelData = $( '.leftPanelData' );
//jQuery window resize call/event
$window.resize(function resizeScreen() {
// console.log('window is resizing');
// here I am resizing my div class height
$rightPanelData.css( 'height', $window.height() - 166 );
$leftPanelData.css ( 'height', $window.height() - 236 );
});
</script>
I consider the jQuery plugin "jQuery resize event" to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It's similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.
The plugin is available here
There are performance issues if you add a lot of listeners, but for most usage cases it's perfect.
I think you should add further control to this:
var disableRes = false;
var refreshWindow = function() {
disableRes = false;
location.reload();
}
var resizeTimer;
if (disableRes == false) {
jQuery(window).resize(function() {
disableRes = true;
clearTimeout(resizeTimer);
resizeTimer = setTimeout(refreshWindow, 1000);
});
}
hope it will help in jQuery
define a function first, if there is an existing function skip to next step.
function someFun() {
//use your code
}
browser resize use like these.
$(window).on('resize', function () {
someFun(); //call your function.
});
Besides the window resize functions mentioned it is important to understand that the resize events fire a lot if used without a deboucing the events.
Paul Irish has an excellent function that debounces the resize calls a great deal. Very recommended to use. Works cross-browser. Tested it in IE8 the other day and all was fine.
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
Make sure to check out the demo to see the difference.
Here is the function for completeness.
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});