What does this block of JavaScript code do? - javascript

I am very new to JavaScript, jQuery and HTML etc. And I am supposed to implement this block of code (below) in a project and I am not quite sure what it is meant to do:
$(document).ready(function(){
$("body").click(function(){
$(this).hide();
});
});
I'm assuming it simply hides any element that is clicked.

You are correct, it hides everything inside of the HTML element. It is also important to note that it is written using jQuery, which is a JavaScript library that has helper functions to make JavaScript more accessible to use.
Here is one line at a time:
Wait for the page to finishing loading in the browser (aka the DOM, or document object model):
$(document).ready(function(){
});
When the user fires the click event on the body element, run the following function:
$("body").click(function(){
});
Hide the body:
$(this).hide();
this (in this context) refers to the body element targeted in the previous line, this is the same as writing: `$('body').hide();
this refers to something different based on the context in which it is used. In this example it is used in an event, so it refers to the element that received that event (body). See W3Schools.
.hide() is a built in jQuery function that sets the element to display: none;

$(document).ready is called when the page is ready for javascript to be executed. $("body") selects the body, the body of the document is where all of the visible HTML elements are shown. The click event is triggered when well, the element is clicked. $(this) selects the current element being operated on, which is the body. the hide function hides the selected element, which in this case is the body. So this code hides the body of the HTML page resulting in all visual elements being hidden.

It's simple, it puts an "on click" event on the body element.
So that means, when you click the body element. It will hide everything in between the opening <body> and the closing </body> tags
<body>
<!--everything in here will be hidden once body element is clicked-->
</body>

That code will make it so that clicking on any element on the page will cause the body element to hide.
That is - unless the element has it's own onclick functionality assigned that stops the event from bubbling up to the body element's onclick by using the event.stopPropagation() function.
Note: You could also have a call to event.stopPropagation() within the event handler rather than just having it as the event handler.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("body").click(function() {
$(this).hide();
});
});
</script>
<html>
<head>
<title>Testing javascript function</title>
</head>
<body>
<p>Here is one paragraph</p>
<p>Here is a second paragraph</p>
<p>Clicking on any element will hide the entire body element.</p>
<input type="button" value="random button" onclick="event.stopPropagation()" />
</body>
</html>

It is pretty straight forward.
Sample HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
...
</body>
</html>
Js:
$(document).ready(function(){ //executes when document model is ready
$("body").click(function(){ //once u click anywhere on the page this function will be executed
$(this).hide(); //hides everything between <body></body>
});
});

Related

Second page does not work with Codes in the first page

I have a main page that I have loaded another page on it via ajax when document is ready ,also I have a button that when I click It I shows an alert and, I have that button in the second page too. but when i click on it in that page that code does not work ?
how can i solve this problem ?
because I do not want to repeat js codes on the second page ?
here is my first page code :
first page code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="captcha" style="border:1px solid red;">
</div>
<div class="details1">cccc</div>
<script>
$(document).ready(function(e) {
$(".captcha").load("/secondpage.htm");
$(".details1").click( function()
{
alert('button clicked');
}
);
});
</script>
</body>
</html>
and this is my second page that I have loaded into div with classname captcha:
second page code:
<html>
<head>
</head>
<body>
<section class="details1"> Details </section>
</body>
</html>
When you need to create new elements on-the-fly, you can not use standard click etc. events. Dynamically created elements are not born with the same event handlers as the existing elements. You have to dynamically attach event handlers to newly created elements.
Replace 'click' with 'on'.
$("body").on("click", ".details1", function(){
alert('button clicked');
});

fadeToggle with text() bug?

I'm trying to make a fadeToggle effect on jQuery,
the toggle effect works fine only in the second click on the <h1> tag.
in the first click it showing up and hide right after.
noticed that if I remove the text("how are you") method and put the inside the paragraph tag, it works perfectrly.
wondering why it doesn't work the first way.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('h1').click(function(){
$('p').text("how are you").fadeToggle(500);
});
});
</script>
</head>
<body>
<h1>Hello jquery</h1>
<p></p>
</body>
</html>
fadeToggle works the same way as e.g. toggle (applies opposed attribute). And since the default state for the p element at the begininng is display: inline (is visible), then the next default action will be hiding it. That's why you have to define it initially as hidden.
$(document).ready(function() {
$('h1').click(function() {
$('.x').text("how are you").fadeToggle(500);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello jquery</h1>
<p class='x' hidden></p>
It works correctly actually - the paragraph element is shown and by clicking on the heading, the function inserts text in it and then toggles fade. As the element is shown, by default (since there are no rules attached to it that would otherwise hide it), the fadeToggle will transition from shown to hidden state.
As stated in the comment above, to make fadeToggle begin by fading an element in, you should first hide the element (either via CSS or via JS, depending on your needs).

Jquery closing on parent click

I want a window to close only when pop_up is clicked (as opposed to clicking div contents). E.g. clicking the background layer hides the div. In the code below I don't want it to close #pop_up when clicking the div contents bot only on "pop_up".
How can I do this?
$("#pop_up").click(function() {
$("#pop_up").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pop_up">
<div id="pop_up_content">
<h1> world </h1>
</div>
</div>
What you are experiencing is the bubbling and capturing behaviour of events.
Check this answer What is event bubbling and capturing? .
The simples approach would be to attach a onClick to the child and stop the bubbling.
$("#pop_up_content").click(function(ev) {
ev.preventDefault()
ev.stopImmediatePropagation() // best to use to stop other event listeners from being called
});
You can use the event argument of the click, and see if the click is inside another element (or it is the element itself)
JSFiddle: https://jsfiddle.net/32mz2x3x/1/
$("#pop_up").click(function(event) {
if ($(event.target).parents().andSelf().is('#pop_up_content')) {
return
}
$("#pop_up").hide();
});
I have used parents to check if where you click is inside pop_up_content element, and I used andSelf because maybe you click on #pop_up_content (and not inside it)
More info:
jQuery andSelf function
jQuery is function
jQuery parents function
jQuery event object
use the form that allows a filter selector, combined with :not():
$("#pop_up").on('click', ':not(#pop_up_content)', function (e) {
$("#pop_up").hide();
});
JSBin: http://jsbin.com/hoyizos/edit?html,css,js,output
$("#pop_up").click(function(e) {
if ($(event.target).is($("#pop_up"))){
$("#pop_up").hide();
}
});
h1{
margin:50px 50px;
background-color:red;
display:inline;
}
#pop_up_content{
background-color:yellow;
}
#pop_up{
margin:10px;
background-color:green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
</head>
<body>
<div id="pop_up">
<div id="pop_up_content">pop_up_content
<h1> world </h1>
</div>
I am the pop_up!
</div>
</body>
</html>
Don't cancel event bubbling!: The Dangers of Stopping Event Propagation, use it only if there is no other way.
Don't use andSelf() if you plan to use jQuery 3.x, because it is deprecated since v1.8 and will be removed in jQuery v3.
Note: This function has been deprecated and is now an alias for
.addBack(), which should be used with jQuery 1.8 and later.
If you use jQuery 1.8 < use addBack instead.

Javascript Function Not Being Called after dynamic loading

I have a weird issue that i am hoping someone can help resolve.
Problem
When i load html dynamically via .load() function, if any aspect of html in the loaded fragment tries to access the javascript query functions in original HTML page, it doesn't work. Example code below:
Main HTML page (main.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<!--javascript load functions etc... standard header stuff -->
</head>
<body>
<div id="dynamic_section_fragment"></div>
Load Fragment
<script type="text/javascript">
// <![CDATA[
function loadFragment() {
$("#dynamic_section_fragment").load("/api/fragment/");
};
$(".checkvalue").click(function () {
$.getJSON("/api/checkvalue", {term: $(this).attr('value')}, function () {
console.info("submitted for checking");
})
});
// ]]>
</script>
</body>
</html>
FRAGMENT File (fragment.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
</head>
<body>
<div th:fragment="check_value">
<br/>
Check the value in the attribute field
<br/>
<a href="javascript:" th:attr="value='123'" class="checkvalue">Check This<a/>
</div>
</body>
</html>
SPRING MVC Controller Method
#RequestMapping("/api/checkvalue")
public String getFragment(Model model) {
return "fragment :: check_value";
}
So a run down of actions:
-Main.html page loads
-User clicks on Load Fragment hyperlink
-Javascript dynamically loads the relevant fragment into the div
-User clicks on Check This hyperlink, nothing happens
Is there something i am missing or something i need to be aware?
It is as if Thymeleaf has preregistered all the possible scenarios of events and doesn't allow any others.
Only way i have been able to get it to work is by injecting the "checkvalue" javascript within the fragment, which as you can agree is a bad way of doing things.
Help is appreciated.
You are applying the click event listener to all existing objects with the checkvalue class.
$(".checkvalue").click(function ()
What you rather wish to do (to make the click event apply to all the existing and any new added, dynamically) is to set a event on a parent in the dom tree (parent both to the existing and to all that will be added).
In your case, the body tag would probably be the safe bet.
The following should suffice:
$('body').on('click', '.checkvalue', function() { ...
Simplified, the code will apply a listener on the body element instead of the .checkvalue objects, and whenever a object with the .checkvalue class is clicked (wether dynamically or statically loaded), the event will fire.
edit
I would also suggest that you, in your javascript, don't use jquery before you know for certain that it is loaded.
The jquery lib have a way of fixing this for you, by using the $( document ).ready() function:
$( document ).ready(function() {
// All jquery dependant code here.
});

click event does not fire on newly created li tags

With the following code:
<!DOCTYPE html>
<html>
<head>
<title>test list</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<style>
li{
display:inline;
}
</style>
<body>
<input type="hidden" value="4" id="value">
<ol></ol>
<button id="btn2">increase</button>
<button id="btn1">show</button>
<p></p>
</body>
<script>
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
$("#btn2").click(function(){
var text="<li> -> kkk</li>";
$("ol").append(text);
});
$("#btn1").click(function(){
$("p").text($("li").length);
});
</script>
</html>
any newly created "li" tags that appear after clicking "increase" button, do not trigger handlers bound to the click event.
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
Can you please tell me the reason why it's not work. And is it possible to make it work? If yes, How? Thank you very much.
Try like this : As your 'li' are generating dynamically ( For further reading )
$("body").on('click','li',function(){
$(this).nextAll().css({"color":"red"});;
});
From jQuery documentation: "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next."
try this code:
$(document).on('click', 'li', function(){
$(this).nextAll().css({"color":"red"});;
});
May help to put your script library before the closing body tag
...
increase
show
...
see here: fiddle link
$(function() {
$("#btn2").click(function(){
var text= " --> ";
$('ol').append('<li>'+text+'</li>');
$('ol li:not(":first")').css('color','red');
});
$("#btn1").click(function(){
$("p").text($("li").length);
});
});

Categories