Below is my code that is suppose to be a script that changes the color of the square after you click on in using toggleclass() method in jquery. I think my code is right but I can not get the square to change color. what am I doing wrong? thanks
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" language="javascript">
<script>
$( "p" ).click(function() {
$( this ).toggleClass( "p.over" );
});
</script>
<style>
p { background:#DAA520; font-weight:bold; cursor:pointer;
padding:5px;width:20%;}
p.over { background: #ADFF2F; }
span { color:red; }
</style>
</head>
<body>
<p>Click or double click here.</p>
<span></span>
</body>
</html>
Fix the toggleClass call, you only need the class name, not the selector: toggleClass('over') instead of toggleClass('p.over').
Then, you have two opening script tags:
<script type="text/javascript" language="javascript">
<script>
Remove the first one.
Next, you're binding an event listener to an element that's not in the DOM yet at the time the script executes.
Simple fix: move the script to the bottom of the page.
Another way: either execute the script when the DOM is ready (by wrapping it inside a document ready callback: $(document).ready()) or use dynamic binding using jQuery's on function.
Here is a working version: http://jsfiddle.net/7g95yvyo/
And the last, but not the least, learn to use browser's console - it will help you tremendeously while learning and debugging JavaScript.
css class is a .whatever rule, You don't have any classes in your CSS definitions, just elements.
.foo { color: puce } /* this is a class */
p { color: chartreuse } /* this is an element */
p.foo { color: aubergine } /* this is an element AND a class */
toggleClass('foo');
You're toggling on element.class, but toggleClass expects ONLY a class, not the element.
Related
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>
});
});
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.
I am trying to identify elements by their tag name, but have trouble executing the toggle property using javascript. Perhaps I am not using toggle() correctly, please explain what I am doing wrong.
<!DOCTYPE html>
<html>
<head>
<style>
h1{
position: relative;
float:left
}
</style>
<script>
var x=document.getElementsByTagName("button");
var hello=document.getElementsByTagName("h1");
x.onclick=function(){
hello.toggle(
function(){hello.style.visibility:visible};
function(){hello.style.visibility:hidden};
)
}
</script>
</head>
<body>
<h1>hello</h1>
<button>Toggle between hide() and show()</button>
</body>
</html>
toggle() is a jquery function that shows hidden elements and vice versa.
To use it you need to add jquery in your html
e.g.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
and then with jquery you can add an event listener to the button:
$('button').click(function() {
$('h1').toggle();
});
HTML
<head>
<style type="text/css>
#import url("style.css") //my main css file
</style>
// css file which contains only color properties.
<link href="theme_blue.css" rel="stylesheet">
</head>
<body>
Click Here to switch color
</body>
CSS (theme_blue.css)
body
{
background-color:#66ccff;
}
JS
$(document).ready(function() {
$("#theme-blue").click(function() {
$("link").attr("href", "theme_blue.css");
return false;
});
});
My problem is, when I click the link, the entire structure of the web page is lost and no color changes happen. I am very new to this technology and need some help from experts. Kindly suggest me solutions to overcome this problem.
Your problem is with your jQuery selector. You are applying the attribute href to all link elements including your main css link. I suggest you give your link and id then update your selector:
html
<head>
<style type="text/css>
#import url("style.css") //my main css file
</style>
// css file which contains only color properties.
<link id="css_theme_blue" href="theme_blue.css" rel="stylesheet">
</head>
<body>
Click Here to switch color
</body>
jQuery
$(document).ready(function() {
$("#theme-blue").click(function() {
$("#css_theme_blue").attr("href", "theme_blue.css");
return false;
});
});
Might I offer another solution that I practice.
I have my style sheets but I change the body class to reflect what I want a particular element to look like.
body.blue_theme #element_1 {
background:blue;
}
body.green_theme #element_2 {
background: green;
}
then I swap out the body class when I want themes to change:
$('#blue-theme-button').on('click', function() {
$(body).removeClass('green_theme').addClass('blue_theme');
}
This method is preferable to me because all styles are loaded at the beginning and there won't be a pause on slower machine when a new stylesheet is loaded.
Lets say you have a two css files in /Content folder.
main-theme.css :
body {
background-color:#fff;
}
blue-theme.css :
body {
background-color: blue;
}
you have a page which uses by default main-theme.css and link element has id #siteTheme, also you have clickable element with id #blueTheme
<link id="siteTheme" href="/Content/main-theme.css" rel="stylesheet" type="text/css" />
Activate Blue Theme
all you need is to write function for #blueTheme click, which changes href attribute value of link element with id #siteTheme:
<script>
$(document).ready(function () {
$("#blueTheme").click(function () {
$("#siteTheme").attr("href","/Content/blue-theme.css");
});
})
</script>
i hope this will help ;) and don't forget to load jquery before writing those scripts.
<script src="/Scripts/jquery-1.10.2.min.js"></script>
I have an element which has to be hidden when JavaScript is enabled. The current code seems like this:
<body>
...
<div id="js-hidden"></div>
...
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$('#js-hidden').hide();
})
</script>
There is the problem, the js-hidden div is visible since the rest of page (and JavaScripts) are loaded.
Can I hide that earlier? This solution is so bad for me, JS user canĀ“t see this element.
PS: I've written the example with using jQuery, it can be in plain JS too, of course :-)
$(document).ready makes it happen after full page loaded you can use
<body>
...
<div id="js-hidden"></div>
...
<script src="jquery.js"></script>
<div id="js-hidden"></div>
<script>
$('#js-hidden').hide();
</script>
Simplest thing:
<style>
.js-hidden {
display: none;
}
</style>
<noscript>
<style>
.js-hidden {
display: block;
}
</style>
</noscript>
Since you cannot use onload event on div I guess the best solution is put your js right after that div...