I have a simple page with three buttons. I wanted to make one function that changes the background color of my page on a click. So i somehow made it work.
I am basically wondering what exactly "this" does when i use it in my changecolor brackets?
I kind of have a feeling what it does but i need more objective knowledge.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Panel</title>
<link rel="stylesheet" type="text/css" href="style.css"></link>
<script src="javascript.js"></script>
</head>
<body>
<h1>THIS IS SOME TEXT</h1>
<h2>This is some more text</h2>
<button class="buttons" id="button1" onclick="changecolor(this)">;P</button>
<button class="buttons" id="button2" onclick="changecolor(this)">;]</button>
<button class="buttons" id="button3" onclick="changecolor(this)">;)</button>
</body>
</html>
My css:
h1{
background-color: blue;
float: left;
}
h2{
color: blue;
float: left;
width:100%;
}
.buttons{
float:left;
margin-right: 10px;
width: 25px;
height: 25px;
}
#button1{
background-color:green;
}
#button2{
background-color:darkgray;
}
#button3{
background-color:blue;
}
My javascript:
function changecolor(clickedButton){
if(clickedButton.id == "button1"){
document.body.style.backgroundColor="lightgreen";
}
if(clickedButton.id =="button2"){
document.body.style.backgroundColor="gray";
}
if(clickedButton.id =="button3"){
document.body.style.backgroundColor="lightblue";
}
}
Thank you in advance!
In JavaScript this always refers to the “owner” of the function we're
executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its
owner is the page, or rather, the window object (or global object) of
JavaScript. An onclick property, though, is owned by the HTML element
it belongs to.
Via- http://www.quirksmode.org/js/this.html
this references the DOM element the event occurred on.
In this case, inside changecolor(), clickedButton will reference the <button> object that was clicked.
It sends a reference of the clicked element to the javascript function.
this refers to the button element itself.
this is changing your background color for the body of the document. "this" as in this button or object
Related
I would like to add a property directly to a class instead of objects that have given class.
It should work for dynamically added elements as well.
I tried to do it by using $(".myElement").css("background", "green"); but it works only for already existing elements, the new elements are created with default class properties.
My code is:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<style>
.myElement{
width: 20px;
height: 20px;
background: red;
margin: 5px;
}
</style>
</head>
<body>
<div id="elementsContainer">
<div class="myElement"></div>
<div class="myElement"></div>
</div>
<button id="addClassProperty">Add class property</button>
<button id="addNewElement">Add new element</button>
<script>
$("#addClassProperty").click(function(){
$(".myElement").css("background", "green");
});
$("#addNewElement").click(function(){
$("#elementsContainer").append("<div class='myElement'></div>");
});
</script>
</body>
</html>
The expected result should add a new property to all existing element and to every newly created elements without cast change property for newly created element.
Is there any way to solve this problem?
This is far simpler by adding a class to the parent container and a corresponding css rule for .myElement when that class exists
$("#addClassProperty").click(function() {
$('#elementsContainer').addClass('active')
});
$("#addNewElement").click(function() {
$("#elementsContainer").append("<div class='myElement'></div>");
});
.myElement {
width: 20px;
height: 20px;
background: red;
margin: 5px;
}
.active .myElement {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elementsContainer">
<div class="myElement"></div>
<div class="myElement"></div>
</div>
<button id="addClassProperty">Add class property</button>
<button id="addNewElement">Add new element</button>
Rather than "change class property", you want to change/add a css rule.
EDIT: better link --> Changing a CSS rule-set from Javascript
Or you could have one/multiple classes with existing css and change your objects' classes instead.
When you apply a green background color to elements, the style of the background color is entered into the style attribute. This is how the css() method works. Therefore, each new element has a background color of red, taken from the css.
To solve your problem, you can use the method with adding a class, or change the color of the background rule in the CSS itself. This can be done using cssRules by referring to the document. Like this:
[...document.styleSheets[0].cssRules].find((currentSel) => (currentSel.selectorText = ".myElement")).style.background = "green";
By placing this code inside the click event of the selector #addClassProperty.
$("#addClassProperty").click(function () {
[...document.styleSheets[0].cssRules].find((currentSel) => currentSel.selectorText = ".myElement").style.background = "green";
});
$("#addNewElement").click(function () {
$("#elementsContainer").append("<div class='myElement'></div>");
});
.myElement {
width: 20px;
height: 20px;
background: red;
margin: 5px;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<style></style>
</head>
<body>
<div id="elementsContainer">
<div class="myElement"></div>
<div class="myElement"></div>
</div>
<button id="addClassProperty">Add class property</button>
<button id="addNewElement">Add new element</button>
</body>
</html>
I'm trying to make a simple HTML file with a checkbox and a javascript that change the color of the checkbox when clicked. The problem is that the javascript file is not called, so clicking the button is useless as the javascript code is not being read. It seens very simple but I can't see what am I doing wrong:
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="and_gate.js" defer></script>
</head>
<body style= "background-color: white;">
<label id=in1 class="container1" onclick="in1(element1)">0
<input type="checkbox">
</label>
<style>
.container1 {
background-color:green;
font-size: 2vw;
}
</style>
</body>
</html>
Javascript code:
alert('clicked')
funtion in1(element1){
element1.style="background-color:red;"
}
In an inline event handler, you can use this to refer to the target of the event.
You also misspelled function. And the alert needs to be inside the function.
function in1_fun(element1) {
alert('clicked')
element1.style = "background-color:red;"
}
.container1 {
background-color: green;
font-size: 2vw;
}
<label id=in1 class="container1" onclick="in1_fun(this)">0
<input type="checkbox">
</label>
It's also not a good idea to use the same name for your function as the ID of the element. Both of these become global variables, and it's possible for the ID variable to replace the function variable.
In JavaScript and HTML, when you pass a JS function to the onclick property of an element, the function doesn't know about the element that's calling it. You need to pass it some way to find that element, like an id (or the outer context through this, which I missed, and as Barmar points out in his excellent answer).
You can then use this ID with a function like document.getElementById() to find the desired element in the DOM, and do something with it, in this case change it's style property.
You also misspelled function as "funtion", which will cause it not to be processed as a function.
function in1(id) {
document.getElementById(id).style = "background-color:red;"
}
<!DOCTYPE html>
<html>
<head>
<script src="and_gate.js" defer></script>
</head>
<body style="background-color: white;">
<label id=in1 class="container1" onclick="in1('in1')">0
<input type="checkbox">
</label>
<style>
.container1 {
background-color: green;
font-size: 2vw;
}
</style>
</body>
</html>
The thing is for js purpose I want a particular <style> tag to be removed from my document on an event. So for that, within my knowledge, I have added a class for it and removed on my event, eg:
<style class="custome_for_remove">
.selected_par>td,
.footer-tr>td {
position: relative;
display: table-cell!important
}.....
</style>
<script>
function customeRemove() {
$('.custome_for_remove').remove()
}
</script>
My concern is this HTML standard, is this a proper method.? I couldn't find any questions or answer related to this.
Yes! This totally works and it also seems to be valid syntax. Here's a little demonstration. According to https://validator.w3.org/ having a class in your style tag is considered valid html (you can also use an id if you want).
$("#test").click(() => {
$(".customClass").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style class="customClass">
p {
color: red;
}
</style>
<p>
Test
</p>
<button id="test">
remove
</button>
You can try the below code. It removes CSS perfectly.
function removeJs(){
$(".custome_for_remove").remove();
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<style class="custome_for_remove">
p {
color: red;
cursor: pointer;
}
</style>
<p onclick="removeJs()">
Click here!
</p>
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class="dropdown-content">
<a>1</a>
<a>2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.dropdown-content')){
alert("foo");
}
};
</script>
</body>
</html>
I'm trying to make alert(foo); execute only when we are NOT clicking on anything inside of the div tag in the body. Unfortunately, it executes no matter where I click. Why?
window.onclick = function(event){
if (document.getElementsByClassName('dropdown-content')[0].contains(event.target)){
// inside
} else{
// outside
alert('foo');
}
};
.dropdown-content a{
display: block;
background-color: blue;
}
<div class="dropdown-content">
<a>1</a>
<a>2</a>
</div>
Get your element and use contains to check whether click is in or outside. If outside then alert.
matches is not working because you are clicking in a tag which is not having .dropdown-content tag. So everytime value comes false. And it alert('foo')
As i seen you have to add content to de div.conta, i made a demo
And work with the dom, className( imade right, but can use any):
<div class="dropdown-content">
abc
<a class="name">1</a>
<a>2</a>
</div>
window.onclick = function(event){
console.log(event.target.className);
if(event.target.className!=='dropdown-content'){
console.log("foo");
}
};
If you're using jQuery you can do the following:
$(event.target).closest('.dropdown-content').length
See the following JSFiddle:
https://jsfiddle.net/4nb691a0/
Because your if statement returns false and with ! operator returns true. It happens because when you clicked inside the div your actual target is <a> element which does not have class .dropdown-content.
When click outside the div it also does not have class .dropdown-content. So your statement always returns false but with ! operator it becomes true.
Try this:
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class="dropdown-content">
<a class="link">1</a>
<a class="link">2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.link')){
alert("foo");
}
};
</script>
</body>
</html>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Working With DOM</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#gold").addClass("highlight");
});
</script>
<style type="text/css">
body{background-color:#FFCC66;}
#wrap
{margin:0 auto;
border:2px solid #CC8320;
height:500px;}
h1{font-style:italic;
color:#A48713; padding-left:10px;}
#gold{width:200px;
background-color:#D49F55;
height:150px; margin:20px; float:left;height:200px}
input{border:1px solid black; width:150px; margin:0 20px;
background-color:#AA9F55; color:#553F00;font-weight:bolder;text-align:center; }
.info{border:1px solid black; width:150px;background-color:#AA9F55; color:#553F00;font-weight:bolder;text-align:center;margin:0 20px; }
.highlight{background-color:green;}
</style>
</head>
<body>
<div id="wrap">
<h1> Learning Web Engineering Online</h1>
<div data-price="399.99" id="gold">
<h3>Gold Member</h3>
<ul class="course">
<li>HTML5</li>
<li>css3</li>
<li>jquery</li>
</ul>
<form>
<input type="button" value="GET PRICE"/>
</form>
</div>
</div>
</body>
I am having problem with the code above that when using jquery i add class highlight to element with id=gold and inspect it in chrome, although the class is being added to the code the style rule mentioned in highlight class doesn't output in browser. the element is being selected but not styled. what am i doing wrong please help someone.
You should use !important to work it:
.highlight{background-color:green !important;}
Note:
Browser uses ID with higher importance than a class name.
change your css to
#gold.highlight{background-color:green;}
You need to change the priority style for .highlight. Just add #gold before the .highlight style
#gold.highlight{background-color:green;}
The problem here is due to the precendence of CSS selectors. An id selector will override a class selector, so you need to either make the class selector more specific (preferred method):
#gold.highlight { background-color: green; }
Example fiddle
Or aleternatively add !important to it:
.highlight { background-color: green !important; }
However the latter can lead to issues when you have competing !important rules, so it's best to avoid it where possible.
highlight gets applied but as there is background-color property defined in ID it will not be overridden by class value.
As mentioned by #cocco you can use #gold.highlight to override it.
Id has greater precision due to conflict resolution, class css is overridden by your #gold id css
change your class
.highlight{background-color:green !important;}