This question already has answers here:
How to execute a jQuery code [closed]
(2 answers)
Closed 8 years ago.
I found this function:
function squarifyMe(element) {
squareItUp()
window.onresize = function(element) {
squareItUp();
}
function squareItUp() {
$(element).height($(element).width());
}
}
with this call:
$(document).ready(function() {
squarifyMe('.myElement');
});
but don't know how to add it to my webpage...
I've done this a bunch of times but can't get it to work.
The function named squarifyMe() uses jQuery.
This means the first thing you have to do is import jQuery.
The easiest way to do that is to use a hosted library.
To use Google's hosted version of jQuery, add this to your html page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Alternatively, you could download jQuery and include it yourself.
.
.
.
Now to explain the second piece of code:
$(document).ready(function() {
squarifyMe('.myElement');
});
The first line basically says "execute the following code when the page is ready."
You can learn more by reading the documentation for $(document).ready().
.
.
.
Now to explain the next piece of code:
squarifyMe('.myElement');
function squareItUp() {
$(element).height($(element).width());
}
The first line above invokes the function squarifyMe() with a string as a parameter when the document is ready.
Inside squarifyMe() the function squareItUp() is invoked.
It does the following (piece by piece):
$('.myElement')
This code selects all elements in the document who have the css class myElement.
All such elements are returned as a set, which is manipulated by the chained jQuery code that follows.
You can learn more about selecting DOM elements by class here.
Let's rewrite this line of code for clarity:
$(element).height($(element).width());
We'll rewrite it like this:
var $s = $(element);
$s.height($s.width());
Now $s equals the set of DOM elements who have the css class myElement.
In the second half of the line, we GET the width of each element in $s like this:
$s.width()
You can learn more by reading the documentatino for jQuery.width().
We then SET the height of that element to equal its width like this:
$s.height($s.width());
This will make every element with the class myElement a square.
.
.
.
Now to explain the last piece of code:
window.onresize = function(element) {
squareItUp();
}
This code registers an event handler for window.onresize.
In other words, it causes squareItUp() to get invoked whenever the user resizes the browser window.
So... Every time you resize your browser, every DOM element with the class myElement will become a square.
You can learn more by reading the documentation for window.onresize.
You need to put the whole code in script tags and import the jquery library.
Make sure that the element you want to "square" has the class "myElement". If it has the id "myElement", you need to change ".myElement" to "#myElement".
Oh, and you need to resize the page to run the function.
Try it.
squarifyMe.call('.myElement');
Related
I have a piece of HTML that contains some JavaScript
<div id=’abc’> Hello World</div><script> myfunction() { alert (“hi”);}</script>
This is loaded/injected into a target div that is in an iFrame, via an Ajax call that gets the above html.
<iframe id=’myiFrame’><div id=’targetDiv’></div></iframe>
So I’d have something like
<iframe id=’myiFrame’><div id=’targetDiv’><div id=’abc’> Hello World</div><script> function myfunction() { alert (“hi”);}</script></div></iframe>
This all works
My question is. How do I execute myfunction() at some later point in time. How do I find/reference the embedded JavaScript.
I know there are a lot of ifs and buts in this question. Please assume the DOM is ready etc.
I will try to execute myfunction() from an already loaded piece of JavaScript
(function(myframework, undefined ) {
myframework.ButtonClickMethod = function()
{
//this is the call to the dynamically loaded method
//but how do I find / reference this method
myfunction();
}
}(document.myframework = document.myframework || {} ));
Note: myframework.ButtonClickMethod is called from a button click at a time well after all HTML and script has been loaded.
The problem is also complicated by the fact that I cannot control where the piece of injected HTML/Javascript is placed. It has to go into the target div.
I can use JQuery, but prefer vanilla JavaScript.
Also, please ignore any typos in the question, I typed it in Word, it's put ' in etc. It's the mechanism of how to do it I'm interested in.
A less than appealing solution would be to use jQuery to select the script tag html contents. Then use something likethis answer to make it into its own function.
(First of all sorry for my English) I can understand assigning JQuery objects that found by JQuery selectors, to a variable has better performance then using JQuery Selectors every time. The part that i cannot understand is how JQuery detects changes that are not manipulated by JQuery? Here is an example:
<div id="divState">First State</div>
$(document).ready(function () {
var testElement = $("#divState");
alert(testElement.text());//alerts "First State".
document.getElementById("divState").innerHTML = "Second State";//Div has changed outside of the JQuery object.
alert(testElement.text());//alerts "Second State"??? How a variable detects changes.
});
Well, it knows, but it doesn't know . . .
As Blazemonger points out, when you create a jQuery object, one of the items in the object is, essentially, just a pointer to the actual DOM element in the page. So, like you show in your example, any time you inspect the properties of that object, it will inspect the element and show you whatever they currently are. If they change in between checks, you will see the difference.
However, jQuery is not 100% smart . . . if you were to change something fundemental to the selector, it is not smart enough to know to update the collection of objects, without re-selecting them. For example, look at this HTML:
<div id="container">
<div class="similarDivs">Div 1</div>
<div class="similarDivs">Div 2</div>
<div class="similarDivs">Div 3</div>
</div>
If you run the following code against it:
var $mainGroup = $("#container");
var $subGroup = $mainGroup.find(".similarDivs");
console.log($subGroup);
. . . your console would show: Object[div.similarDivs, div.similarDivs, div.similarDivs]
But, if you were to follow that up with this code:
$mainGroup.children(":eq(0)").removeClass("similarDivs");
console.log($subGroup);
. . . your console would show: Object[div, div.similarDivs, div.similarDivs]
It is smart enough to see that the 1st div is no longer tagged with the "similarDivs" class, but it is not smart enough to know that, technically, that means that it should no longer be part of the $subGroup selection group. Again, this is because the selector created a bunch of jQuery objects that point to all of the DOM elements that matched the selection criteria, at a single point in time.
The only way that you could get $subGroup to reflect the change in its collection is by re-running the selector:
$subGroup = $mainGroup.find(".similarDivs");
console.log($subGroup);
. . . resulting in: Object[div.similarDivs, div.similarDivs]
One of the biggest reasons that this is so important (apart from knowing that when you use selectors :) ), is because Javascript does NOT behave that way . . . if you were to write a similar set of functionality in JS, you would get different results:
var mainGroup = document.getElementById("container");
var subGroup = mainGroup.getElementsByClassName("similarDivs");
console.log(subGroup);
mainGroup.children[1].className = "";
console.log(subGroup);
That code would give you:
HTMLCollection[div.25dd58, div.25dd58, div.25dd58]
HTMLCollection[div.25dd58, div.25dd58]
. . . without needing to "re-select" the elements (note: it is also returning an HTMLCollection, not a jQuery Object, which clues you in to the difference in behavior).
As I understand it, the jQuery object contains the DOM node, which is itself a live object. So changing the properties of the DOM node is reflected in the jQuery object.
If you were to .clone() the jQuery object, you'd get the behavior you're expecting:
$(document).ready(function() {
var testElement = $("#divState").clone(); // copy the object and store it
alert(testElement.text()); //alerts "First State".
document.getElementById("divState").innerHTML = "Second State"; //Div has changed outside of the JQuery object.
alert(testElement.text()); //alerts "First State" again
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divState">First State</div>
jQuery is NOT a different programming language. Its a library built on Javascript.
testElement.text() do not detect any change it simply picks the text of testElement and display to alert
I am fairly certain that testElement is just instructions on how to find the DOM element using good old JavaScript, which is faster than finding it via the jQuery selectors.
So every time you work with it, it finds it anew.
Please correct me if I am wrong, that is just an assumption I have based on experience rather than knowledge.
I'm trying to figure out how to connect this line of HTML (which activates a hover pop-up) code which is being used in a PHP file, to the following jquery code. I've gotten it to work for in a single hover instance, but I plan on having multiple hovers all across the page.
HTML Code:
<a class="que" href="http://www.google.com">okok</a>
<div class="launch">test</div>
jQuery Code:
$(document).ready(function() {
$("div.launch").css({'display':'block','opacity':'0'})
$("a.que").hover(
function () {
$(this).next('.launch').animate({
opacity: 1
}, 500);
},
function () {
$(this).sibling('div').stop().animate({
opacity: 0
}, 200);
}
)
});
Thanks a ton for any help... :)
Just change your jQuery selector to match all elements you want to have that hover effect. The jQuery selector is the part of the jQuery statement that tells you what items to, well, select.
$(selectorGoesHere).takeSomeAction;
The selector matches the same format you use for the CSS, so, for example, any element with class="someClass" will be selected in jQuery with $(".someClass"). The jQuery selector can refer to multiple matching items simultaneously, so the jQuery statement used a moment ago would select every element that has that class and perform whatever action you chose.
If, for example, you wanted to use jQuery to set every div to have a red background, you would use:
$("div").css("background-color","#FF0000");
Broken down, that statement finds every div element (as specified by the selector), then applies the CSS style background-color: #FF0000 to EVERY div in the document.
http://jsfiddle.net/joycse06/hzm5p/1/ is an example of having multiple hover-over effects using your code. Just follow that link for a sample how how your already written jQuery statements are applied to multiple HTML elements.
EDIT: Based on the code below, change your jQuery to match http://jsfiddle.net/hzm5p/5/
jQuery(document).ready(function() {
jQuery("div.launch").css({'display':'block','opacity':'0'})
jQuery("a.que").hover(
function () {
jQuery(this).parent().next('.launch').animate({
opacity: 1
}, 500);
},
function () {
jQuery(this).parent().next('.launch').stop().animate({
opacity: 0
}, 200);
}
)
});
Simply add .parent() to get the the containing p element, then take the .next('.launch') element.
EDIT 2: For jQuery in Wordpress, you need to include the following line somewhere in your functions.php file:
wp_enqueue_script("jquery");
Also, it seems that the jQuery used by Wordpress is designed for "compatibility mode", which means the $ shortcut is by default unavailable. You'll need to use jQuery in place of $, unless you use some of the workarounds mentioned in http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/
EDIT 3: Test for jQuery loading with the following code:
if (jQuery) {
alert("jQuery loaded");
} else {
alert("jQuery not loaded");
}
If it's loaded, then I don't know what to tell you. If it isn't, you need to figure out why in Wordpress and get it loaded, or you'll need to re-write your code to use non-jQuery scripting.
You can just use class que to all <a> tags and launch class to all divs next to that <a> tags.
When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
...I can't use the object $myObject!
This is what I'm doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn't work.
I just want to be able to save an element in a variable and then use it!
Note: some people don't put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(This is a shortcut for jQuery's .ready() method.)
http://api.jquery.com/ready/
As long as the document is loaded, and you have a <div> with the ID comments on the page when it loads, it should work.
Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do $("#comments"); instead of $("div#comments");.
You've only provided snippits of your code, so it is impossible to tell for sure, but the odds are that you are running the code in a <script> element that appears before the <div> element and don't do anything (such as use the ready event) to delay the execution of the code until the div exists.
The result is that you get a jQuery object which found no elements. Move the script element so it is after the div. Just before the end tag for the body is a good place.
The syntax is perfectly valid and should work. Are you dynamically appending the comments div? You should alert( $myObject.length ) to see if it's 0 or 1, if its 0 that means it's never picked up.
You may need to bind the var statement until after dom ready, window load, or your ajax callback.
Well, that syntax is perfectly fine so something else is going on. Can you show your markup? And what do you get if you add an alert($myObject.length)? And one last thing to check... are you running this inside an on-ready handler?
Ok, thanks everyone for that.
I got the solution.
I thought about the order the things were loaded in the DOM and found the solution.
The problem (with the markup) was:
<div id="comments">
<script type="text/javascript">
loadComments(params);
</script>
</div>
The code above was written by PHP!
So it executed the function as soon as the browser read the code.
I already tried to put the script on the end of the page, after the function was called. The funcion was not defined yet.
So, the funcion loadComments should be executed after the div was ready AND after the function was defined.
I wrapped the code between the tags with a .ready(), like this:
<script type="text/javascript">
$(function() {
loadComments(params);
});
</script>
It was a distraction.
Sorry everyone!
Thanks a lot.
If you have the same problem and you didn't understand what I did, ask me. XD
i am using prettify, i am wondering if i can make it work with any code block, not requiring the prettyprint class.
else, how can i attach the class prettyprint dynamically, maybe using jquery. what i want to acheive is similar to stack overflow where code typed in the editor will be "pretty printed" in the preview and output.
i tried
$("#main").delegate("code", "ready", function() {
// this does not seem to run at all?
// intending to add the prettyprint class here
});
$(document).ready(function(){ $('code').addClass('prettyprint'); });
$(document).ready(<func>) runs <func> when the DOM is ready.
$('code') selects all code tags.
.addClass() adds the specified class to any elements it is passed (in this case, all of the code tags).
I don't think delegate() is necessary here. You just need to execute prettyPrint() every now and then to evaluate your preview. One solution might be to use setInterval to apply Prettify after every x seconds. Here's a quick example:
$('textarea').bind('keyup', function(e) {
val = this.value.replace(/<code>/gi, '<code class="prettyprint">');
$('#preview').html(val);
});
setInterval(function(){ prettyPrint(); }, 10000);
This would execute prettyPrint() every 10 seconds. It's not what I'd call perfect, but I think it does what you want. You'd probably also want to clear the interval if the user hasn't typed anything for a certain amount of time, but I hope this is enough to get you moving in the right direction.