$(window).bind("load", function(){} event - javascript

Ok, so I have a parent div that contains two divs. The parent div will naturally be as tall as the tallest child div, dictated by content. However, I want the two child divs to be the same dynamic height, regardless of content. Thus, I resolved to JavaScript it. Here's what I have:
<!--- Make main div's same height -->
<script type="text/javascript">
$(window).bind("load", function() {
setDivHeight() {
var left = $('#primary');
var right = $('#secondary');
var maxHeight = Math.max(left.height(), right.height());
left.height(maxHeight);
right.height(maxHeight);
}
});
</script>
However, when I try to run it, I get this message in my console:
Uncaught TypeError: Property '$' of object [object Object] is not a function
I've been digging into this for about 4 hours now, and I've given up hope...
Can anyone tell me what I'm doing wrong???

It sounds like you don't have jQuery included in the page above that code, or you do but something has taken over the $ symbol.
Ensure jQuery is loaded prior to the code, like so (this is just one link you might use):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
And/or if you have that but something else is using the $ symbol, you can do this with your code:
(function($) {
$(window).bind("load", function() {
// v----- Side note: This looks like a syntax error
setDivHeight() {
var left = $('#primary');
var right = $('#secondary');
var maxHeight = Math.max(left.height(), right.height());
left.height(maxHeight);
right.height(maxHeight);
}
});
})(jQuery);
That uses the jQuery symbol, passing it into a function as the $ argument. Even if $ is something else outside that function, within it, it will be jQuery.
Side note 1: Your code contains a syntax error. Perhaps you meant:
(function($) {
$(window).bind("load", function() {
var left = $('#primary');
var right = $('#secondary');
var maxHeight = Math.max(left.height(), right.height());
left.height(maxHeight);
right.height(maxHeight);
});
})(jQuery);
Side note 2: The window load event happens very late in the load process, after all images are loaded. That may be what you want (for instance, if the height of the divs is partially dictated by images), but if not you might want to use ready instead (in this case, using one of its shortcuts), as it happens sooner:
jQuery(function($) {
var left = $('#primary');
var right = $('#secondary');
var maxHeight = Math.max(left.height(), right.height());
left.height(maxHeight);
right.height(maxHeight);
});
Again, though, maybe you're waiting for the images for a reason.

Related

My Script is not working in wordpress static site

I am working on my wordpress site, and i use a static page for my front/home page. I wanted to use parallax scrolling but i cant get my script to load and work.
I linked it in header like this:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/scroll.js"></script>
and this is my scroll script:
(function($) {
$.fn.parallax = function(options) {
var windowHeight = $(window).height();
// Establish default settings
var settings = $.extend({
speed: 0.15
}, options);
// Iterate over each object in collection
return this.each( function() {
// Save a reference to the element
var $this = $(this);
// Set up Scroll Handler
$(document).scroll(function(){
var scrollTop = $(window).scrollTop();
var offset = $this.offset().top;
var height = $this.outerHeight();
// Check if above or below viewport
if (offset + height <= scrollTop || offset >= scrollTop + windowHeight) {
return;
}
var yBgPosition = Math.round((offset - scrollTop) * settings.speed);
// Apply the Y Background Position to Set the Parallax Effect
$this.css('background-position', 'center ' + yBgPosition + 'px');
});
});
}
}(jQuery));
$('.parallax-section-1').parallax({
speed : 0.15
});
I found some articles that i would have to use the functions.php and enque the script but i never did that before so im a bit lost, so any help would be highly appreciated.
First things first, lets load the script the "WordPress Way". This will actually help simplify troubleshooting.
To do that, edit your theme's functions.php file.
In that file, add this PHP code. Be sure it is between <?php opening / closing tags.
Typically, I'd recommend adding it to the end of the file, but if your file includes this ?> - that the code you add is before the ?>:
add_action('enqueue_scripts', 'my_custom_script');
function my_custom_script() {
// Be sure jQuery is loading
wp_enqueue_script('jquery');
// Load your script
wp_enqueue_script('my-parallax-script', get_template_directory_uri() . '/js/scroll.js', array('jquery'), FALSE, TRUE);
}
Now - once you do this, you will want to be sure that your script is in fact loading. To do that, visit the page, then do a VIEW SOURCE in your browser. When you view source, do a search of the code for "scroll.js" - if you find it, great. Click on the url (or copy / paste it into your browser window) and be sure that the script is referencing the right location. If not, you'll need to be sure to move the script to the right location, so the page will load it.
Next Step
You have a problem with your script that will not work in WordPress. You are referencing jQuery with the $ symbol, AND it appears that you are referencing an element directly, which means there's a good chance the element doesn't exist when the script will run, which means that it won't have the desired effect.
Instead, we need to do two things. Because WordPress loads jQuery in what's called no conflict mode, you need to reference it using jQuery, not $. AND you need to put your code into a document ready function.
Thankfully, jQuery offers a slick way of doing the document ready that exposes the $ inside of the document ready, for convenience:
// Shorthand version of "No-conflict-safe" document ready
jQuery(function($) {
// Inside here, we can use $ instead of jQuery
$('.parallax-section-1').parallax({
speed : 0.15
});
});
If it still does not work after all of this, then you need to open your console in your browser, and look for any javascript errors. They will help you identify what is going on, which is the first step to solving the problem.

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

Javascript onclick event firing for id but not for class

I'm fairly new to Javascript, and am trying to get an 'on click enlarge' kind of effect, where clicking on the enlarged image reduces it again. The enlarging happens by replacing the thumbnail by the original image. I also want to get a slideshow using images from my database later on.
In order to do that, I made a test where I replace the id which indicates enlarging is possible by a class and I also use a global variable so that I can keep a track of the url I'm using. Not sure this is the best practice but I haven't found a better solution.
The first part works fine, my image gets changed no problem, values are also updated according to the 'alert' statement. However, the second part, the one with the class never triggers.
What am I doing wrong (apart from the very likely numerous bad practices) ?
If instead of changing the class I change the id directly (replacing .image_enlarged by #image_enlarged, etc.), it seems to call the first function, the one with the id, yet outputs the updated id, which is rather confusing.
var old_url = "";
$(function(){
$('#imageid').on('click', function ()
{
if($(this).attr('class')!='image_enlarged'){
old_url = $(this).attr('src');
var new_url = removeURLPart($(this).attr('src'));
$(this).attr('src',new_url); //image does enlarge
$(this).attr('class',"image_enlarged");
$(this).attr('id',"");
alert($(this).attr('class')); //returns updated class
}
});
$('.image_enlarged').on('click', function (){
alert(1); //never triggered
$(this).attr('src',old_url);
$(this).attr('class',"");
$(this).attr('id',"imageid");
});
});
function removeURLPart(e){
var tmp = e;
var tmp1 = tmp.replace('thumbnails/thumbnails_small/','');
var tmp2 = tmp1.replace('thumbnails/thumbnails_medium/','');
var tmp3 = tmp2.replace('thumbnails/thumbnails_large/','');
return tmp3;
}
As for the html, it's really simple :
<figure>
<img src = "http://localhost/Project/test/thumbnails/thumbnails_small/image.jpg" id="imageid" />
<figcaption>Test + Price thing</figcaption>
</figure>
<script>
document.write('<script src="js/jquery-1.11.1.min.js"><\/script>');
</script>
<script type="text/javascript" src="http://localhost/Project/js/onclickenlarge.js"></script>
From the API: http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected
set of elements in the jQuery object.
When you do $('.image_enlarged').on(...) there is no element with that class. Therefore, the function is not registered in any element.
If you want to do so, then you have to register the event after changing the class.
Here's an example based on your code: http://jsfiddle.net/8401mLf4/
But this registers the event multiple times (every time you click) and it would be wrong. So I would do something like:
$('#imageid').on('click', function () {
if (!$(this).hasClass('image_enlarged')) {
/* enlarge */
} else {
/* restore */
}
}
JSfiddle: http://jsfiddle.net/8401mLf4/2/
Try using:
addClass('image-enlarged')
instead of:
.attr('class',"image_enlarged");
the best way to do this would be to have a small-image class and a large image class that would contain the desired css for both and then use addClass() and removeClass depending on which you wanted to show.

Cant fix a jquery / javascript bug

I have some jquery code that is picking up some issues in firebug chrome.
any help would be great, please update fiddle.
please see the link with fiddle.
http://jsfiddle.net/jwhTd/
image
/* SHOW CATEGORIES
===================================================================*/
$('.normal-btn\.interest').click(function(e){
// Prevent the event from bubbling up the DOM tree
e.stopPropagation();
$('.categories-wrap').fadeIn(); // must be hidden, to fade in
});
$(document, '.normal-btn\.interest').click(function(){
$('.categories-wrap').fadeOut(); // must be visible, to fade out
});
var offset = $(".sticky-header").offset();
var sticky = document.getElementById("sticky-header")
var additionalPixels = 50;
$(window).scroll(function () {
if ($(window).scrollTop() > offset.top - additionalPixels) {
$('#profile-container').addClass('fixed');
} else {
$('#profile-container').removeClass('fixed');
}
});
It's telling you exactly what is wrong. offset is undefined. You probably expect that it has a value, check why it doesn't have one.
You get more errors though. Something about slider and another about an invalid .top access somewhere.
it looks like most of that code is not in the document.ready. the var offset = $(".sticky-header").offset(); needs to be executed once the dom is ready.
Your code:
var offset = $(".sticky-header").offset();
var sticky = document.getElementById("sticky-header")
var additionalPixels = 50;
The first line selects all elements with the class of sticky-header, then gets the offset of the first one. The .offset() function returns undefined in the event that the selector matches zero elements, which appears to be the case here due to the error you're getting later on.
On the next line you're selecting an element with an id of sticky-header, which makes me think that perhaps your first line should be
var offset = $('#sticky-header').offset();
instead, which uses an ID selector rather than a class one.

Calling JQuery function from different context

This might be a very basic question but I'm trying to understand this behavior
This is my javascript code. I want to know why second call to foo does not work. Here is the JSFiddle link
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function"); //this works
});
$('#container').foo("outside"); //this does not
The DOM is not fully loaded .. Thats the reason it won't work..
So when you encase your code inside the DOM Ready handler it waits for the document to be loaded and then runs the code inside.
This makes sure the element is available before any code is run on it..
When the HTML document is parsed , it parses top down.
So if the script is included in the head section , then the scripts are loaded first and then the HTML structure.. When you try to the run the code , it obviously won't work cause the element was still not parsed..
So encasing that in the handler will make sure the element is available before calling the methods on them..
This is because $('#container').foo("outside"); is evaluated before the body is processed. $('#container') will return with a length of 0. This is demonstrated below.
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function");
});
var element = $('#container');
console.log(element.length); //prints 0
element.foo("outside");
If the script is at the beginning of the page the rest of the HTML document has not been parsed yet, so the document looks empty to the script, so there is no #container yet.
$(function() { ... });
is (roughly) equivalent to
Wait till the whole HTML file is loaded and ready
Then execute function
so #container will be there and it will work. Another way to make it work would be to put the script below the rest of the page or at least below #container.

Categories

Resources