Trouble Understanding JQuery fundamentals - javascript

Can someone explain why in the below code, $(document).ready(function(){ $("#msgid").html(); }); must be called before I can append to the div with my appender function? If I get rid of that part, and press the button, nothing gets appended to the div, this doesn't make sense to me! I thought JQuery's .html() method just returned the HTML contents of the div, so in my below code it would return nothing, and therefore server no purpose.
CODE:
<script type="text/javascript">
$(document).ready(function(){
$("#msgid").html(); //WHY IS THIS CODE BLOCK NECESSARY?
});
function appender(){
$(document).ready(function(){
$("#msgid").append("appended with the appender() function<br />");
});
}
</script>
This is Hello World by HTML
<div id="msgid">
</div>
<input type="button" id="myButton" value="click me" onclick=appender() />
Thanks in advance!

<script type="text/javascript">
$(document).ready(function(){
$("#msgid").html(""); //This is to clear the html code that is inside #msgid
});
function appender(){
$("#msgid").append("appended with the appender() function<br />");
});
}
</script>
This is Hello World by HTML
<div id="msgid">
</div>
<input type="button" id="myButton" value="click me" onclick=appender() />
Hope that helps

You do not need to have the $(document).ready() inside your function. But also, one of the main benefits of jQuery is its event handling, which allows you to stop using the onclick, onmouseoiver attributes in html.
Try:
$(document).ready(function(){
$("#msgid").click(function() {
//This function will be performed whenever the element with id msgid is clicked
$("#msgid").append("appended by an anonymous function attached to the click event of this element");
})
});
OR
$(document).ready(function(){
$("#msgid").click('appender');
});
function appender()
{
$("#msgid").append("appended with the appender() function<br />");
}
Both will achieve the same end, but naming a function saves repeating code as always.

You can greatly simplify your code this way.
$(function() {
$('#myButton').click(function() {
$("#msgid").append("appended with the appender() function<br />");
return false;
});
});

To do what you want , you can do as below
<script type="text/javascript">
$(document).ready(function(){
$("#msgid").html(''); //WHY IS THIS CODE BLOCK NECESSARY? to empty the contents of the div
$("#msgid").click(function() {
appender();
}); // end of click function
}); // end of document.ready
The below functions behaves like a global function and you can call it from anywhere.
function appender(){
$("#msgid").append("appended with the appender() function<br />");
}

Related

How to call a function when a div is dynamically generated using jQuery

The scenario I want to achieve is as follow:
$("#parentDiv").on("load",'#childDiv', function () {
// do something...
});
I would like to call a function when a child div is dynamically generated and shown on the page, but there is no suitable event that can achieve this. Any hint or help would be appreciated.
Instead of load, you can make use of a custom event which gets triggered with .trigger():
$(document).ready(function() {
$("button").on("click", function() {
$("body").append("<div id='new'>Created</div>").trigger('custom-event');
});
});
$(document).on("custom-event", function() {
console.log('DIV created!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Create element</button>
</body>

Calling function from Javascript string

$("#showloader").replaceWith("<span class='iconexclaim'><img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' onclick='abc()'>Retry</span>");
function abc() {
alert("abc");
}
The above code is replacing the html with selected element object, but when I click on retry it is showing function is not defined.
you need to bind the click on the span to the document, this code will help you on that.
$("#showloader").replaceWith("<span class='iconexclaim'><img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' >Retry</span>");
$(document)
.on(
'click',
'.retry-btn',
function() {
alert("I am here") ;
}) ;
If you wrap the abc() inside your head tag or on body load, it will work:
function abc() {
alert("hi");
$("#showloader").replaceWith("<span class='iconexclaim'><img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' onclick='abc()'>Retry</span>");
}
$(document).ready(function(){
abc();
});
FIDDLE
You need to put that function code block somewhere (above it) before you call .replaceWith or manipulate the dom.
Please Try like this :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("#showloader").replaceWith("<span class='iconexclaim'> <img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' onClick='abc()'>Retry</span>");
});
function abc(){
alert("abc");
}
</script>
</head>
<body>
<div id='showloader'>helloo world</div>
</body>
</html>

jQuery show not work

I am trying to show span but it doesn't work. This is the code that doesn't work:
<script>
$(document).ready(function() {
$('input[type="file"]').ajaxfileupload({
'onStart': function() {
//alert("myAlert");
$(this).siblings('span').show();
}
});
});
</script>
But the span will show when I put alert before it, like this:
<script>
$(document).ready(function() {
$('input[type="file"]').ajaxfileupload({
'onStart': function() {
alert("myAlert");
$(this).siblings('span').show();
}
});
});
</script>
Why is this happening? (I use the plugin: jquery.ajaxfileupload)
Edit:
This is my html code:
<input type="file"/><br/>
<h1>test1</h1>
<span style="display: none;">test3</span>
<h2>test2</h2>
The problem is that your code runs before the DOM structure has finished loading. That causes your script to attempt to change the styles of the span before it has access to the span, so it doesn't do anything at all. To fix this, place your code within a callback, like this:
$(function() {
$('input[type="file"]').ajaxfileupload({
'onStart': function() {
$(this).siblings('span').show();
}
});
});
That will make the code run only after everything has loaded, which will ensure that your script can actually access the element it needs to show. When working with the DOM (which is basically everytime you need to change any HTML element), you need to put your code in such callback function.
Try a direct reference to the span
<input type="file"/><br/>
<button>View Span</button>
<h1>test1</h1>
<span class="myspan" style="display: none;">test3</span>
<h2>test2</h2>
Then
<script>
$(document).ready(function() {
$('input[type="file"]').ajaxfileupload({
'onStart': function() {
$('.myspan').show();
}
});
});
</script>
This must work

Calling javascript function

I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.

Why doesn't this click handler work in JQuery?

I've got the following code in my page:
var offer_link = $('<a>').addClass('fc-offer-link');
offer_link.click(function() {
alert('Hello');
});
offer_link.attr('href', "#" + this.id);
offer_link.append(this.subject);
this.list_item = $('<li>');
this.list_item.append(offer_link);
But even though the link appears on the page, the handler never gets called. What's going on?
The problem turned out to be where the item got inserted into the DOM. It was being inserted using:
$('#my_list').html(my_new_list.html())
It should have been using:
$('#my_list').replaceWith(my_new_list)
I think you just need to append the link to an element, like this:
<script type="text/javascript">
$(function(){
var link = $("<a>Click Me!</a>").addClass("fc-offer-link").appendTo($("#div1"));
if (link){
link.click(function(){
alert("Hey there!");
});
}
});
</script>
<div id="div1"></div>
EDIT: Not sure why I was downvoted, but here's a jsFiddle

Categories