Why the JavaScript function doesn't work? - javascript

If you click the button, it should have showed, but it doesn't.
Is any wrong here?
I have written many JavaScript files in this way, and tried many ways like changing the position of JavaScript code anywhere. But all the files I wrote don't work
Thanks in advance!
An instance :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class = "show" onclick = "JavaScript : show();">Show</button>
<script type = "text/JavaScript">
function show() {
document.querySelector("debug").style.display = "flex";
}
</script>
</body>
</html>
Thanks to all of you!

About .querySelector()
The Document method querySelector() returns the first Element within the document that matches the specified selector. [...] The selector is a CSS selector string.
- MDN web docs
You should, therefore, put in your code:
document.querySelector(".debug")
You can also select HTML elements by their tags, for example, you want to select the first div:
document.querySelector("div")
document.querySelector("div").style.color = "lightgreen"
<div>Hello World</div>
Imagine you had your own HTML tag: <hello>, then you can select all hello elements with:
document.querySelector("hello")
document.querySelector("hello").style.color = "lightblue"
<hello>Hello World</hello>
Side note on inline eventListeners
Also in HTML for inline event listener instead of:
<button class = "show" onclick = "JavaScript : show();">Show</button>
you can simply write:
<button class = "show" onclick = "show();">Show</button>
It is recommended to use JavaScript to initiate these eventListeners instead of having them inline inside your HTML markup. Use the .addEventListener() method:
document.querySelector(".show").addEventListener('click', show)
↑ ↑
event function
type
Back to your code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class ="show">Show</button>
<script type = "text/JavaScript">
document.querySelector(".show").addEventListener("click", show)
function show() {
document.querySelector(".debug").style.display = "flex";
}
</script>
</body>
</html>
Last thing
Also it's better to keep HTML, JavaScript and CSS all in separate files, for instance:
- index.html
- style.css
- script.js
And call the CSS and JavaScript files in your HTML file with the link (preferably inside <head>) and script (at the bottom of <body>) tags:
<link rel="stylesheet" type="text/css" href="style.css">
And
<script src="script.js"></script>

For class selector you need to add a dot (.) e.g. .debug
Also, in HTML, you can simply have onclick as onclick="show();"
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="show();">Show</button>

You were not passing class to querySelector. Set ".debug" instead of "debug".
Below is working code:
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="JavaScript : show();">Show</button>

queryselectors requires . and # for class and ID selector:
querySelector(".debug")

Related

How do I prevent a Slotted HTML element from rendering until is it inside the shadowRoot?

I have a very simple site similar to this jsfiddle. Everything seems to work fine but on my local one, but when I stop at the first JS line (before the custom elements are declared) I can see the div with no formatting...
<jrg-test>
<div slot="test">
This should work
</div>
</jrg-test>
connectedCallback() {
console.log("Ok we are working")
this.shadowRoot.innerHTML = "<slot name='test'></slot>"
const element = document.createElement('style');
element.textContent = "::slotted(*){background-color:red;color:white;}";
this.shadowRoot.appendChild(element);
}
So basically if I stop before the custom element is rendered I see the raw div. I know there are some hacky solutions involving positioning and CSS but is there a cleaner solution. Possibly one I can implement exclusively in JS?
So the main question is how can I hide the This should work text until the red background and white color have been applied?
Maybe you could try to use the :defined CSS pseudo-class to hide the custom element while it's defined.
See the example below:
class TestElement extends HTMLElement{
constructor(){
super();
console.log("Attaching the shadow")
this.attachShadow({mode:'open'})
}
connectedCallback() {
console.log("Ok we are working")
this.shadowRoot.innerHTML = `<style>
::slotted(*){background-color:red;color:white;}
</style>
<slot name='test'></slot>`
}
}
upgrade.onclick = () => customElements.define("jrg-test", TestElement)
jrg-test:not(:defined) {
display:none
}
<jrg-test>
<div slot="test">This should work</div>
</jrg-test>
<button id="upgrade">upgrade</button>
You can hide all not defined customElements with adding to global styles
<style>
*:not(:defined) { display:none }
</style>
For example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style> *:not(:defined) { display:none } </style>
<script type="module" src="./index.js"></script>
</head>
<body>
<test-tag>
This content will be visible only after "test-tag" is defined
</test-tag>
</body>
</html>

js: element.className does not work (create a dark mode)

I want to change the css properties of many html objects (but in this example I only took body to simplify. My goal is to display dark mode if the current mode is light, or display light mode if current mode is dark.
My javascript function does not work.
debug.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="debug.css">
<script src="darkmode.js"></script>
</head>
<body id="bodyElem" class="my-body light-mode">
<h1>Settings</h1>
<p>Dark mode:</p>
<button type="button" onclick="invertMode()">click</button>
</body>
</html>
debug.css:
.my-body.light-mode{
background-color: yellow;
}
.my-body.dark-mode{
background-color: black;
}
darkmode.js:
function invertMode() {
var body = document.getElementById("bodyElem");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}
You will need to add an ID for the <body> tag to be able to find it using your code.
<body id="bodyElem" class="light-mode">
and access it using:
var body = document.getElementById("bodyElem");
If you need to access mutiple elements, you can use their CSS class name like:
document.getElementsByClassName("CLASSNAMEHERE");
then loop them all to apply the changes you need.
you will be using .classList.remove("CLASSNAME") to remove single class and .classList.add("CLASSNAME") to add single class to DOM element
Here is a complete sample fiddle:
https://jsfiddle.net/j3o8Lt5k/1/

Setting and removing the onclick attribute

So I am trying to remove the onclick attribute from the div "#link". It will not remove. It also will not work with setting an attribute for onclick. Anything that seems to edit onclick doesn't seem to effect it. I need it to remove the attribute of "of onclick" and set it to another one. Thanks
$(document).ready(function() {
var attribute = $('#link').attr("onclick");
var linklength = (attribute.split("'").length - 1);
if (linklength > 5) {
$('#link').removeAttr("onclick");
$('#link')[0].setAttribute('onclick', 'test');
console.log(attribute);
console.log(linklength);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="link" onclick="skinPopup('UserDirectory','for name ','#userBio');">
</div>
<p id="title">Te'st</p>
Not sure what you are trying to achieve, as you already using jQuery you could simplify things. Something like this
$(document).ready(function() {
var $link = $("#link");
function skinPopup(directory, statement, id){
console.log(directory, statement, id);
}
$link.on('click', function(){
skinPopup('UserDirectory','for name ','#userBio');
});
//removing click event after 3s
setTimeout(function(){
$link.addClass('red');
$link.off('click');
// attaching mouseover and mouseout event
$link.on('mouseover', function(){
$(this).removeClass('red');
}).on('mouseout', function(){
$(this).addClass('red');
})
}, 3000)
});
.red{
background: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="link">
Link
</div>
<p id="title">Te'st</p>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Note, instead of removing click event on condition I removed it after a particular time, you could add condition based on your requirements. Both attribute and linklength seemed unnecessary, that's why I removed it.
To learn more about event listeners
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
http://api.jquery.com/on/
http://api.jquery.com/off/
Hope this helps, let me know if you have any questions.

javascript style button not functioning

I cannot get my javascript to run. I have added several different options, and removed them, I have had the function in the and now moved it to the . No matter what I try the button does not work. I am trying to learn javascript. It doesn't seem that difficult to learn, but If I can't test it, what is the use? Please help!
<!DOCTYPE HTML> 
<html>
<head> 
<meta charset=utf-8 /> 
<title>Change Paragraph Text</title> 
</head>  
<body> 
<p id ="text">I’m going to change this text, I hope.</p> 
<button type="button" onclick="js_style()">Click on Me</button> 
<script>
function js_style() {
'use strict';
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
document.getElementById("text").innerHTML = js_style();
</script>
</body> 
</html> 
The code you present throws undefined on the text you want to change. Simply remove
document.getElementById("text").innerHTML = js_style();
and everything should work, I suppose. Here is an example:
https://jsfiddle.net/nmLrpvhy/
The issue is that you have this line:
document.getElementById("text").innerHTML = js_style();
running automatically (because it's outside of your function) and changing the text immediately, so clicking the button does work, but it's just setting the same styles that were already set.
Additionally, innerHTML is for setting the "content" of an element, not its style. In your case, that line attempts to set the return value from the js_style function as the value for the innerHTML. But, the function doesn't return a value - - it only concerns itself with modifying styles.
Don't use inline HTML event attributes (onclick, etc.). See here for why. Instead, do all your work in JavaScript.
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button">Click on Me</button>
<script>
// get a reference to the button
var btn = document.querySelector("[type='button']");
// set up the click event handler
btn.addEventListener("click", js_style);
function js_style() {
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
</script>
</body>
</html>
here is the solution of your code:
the line in which you were trying to get your changed text was actually outside the scope of the 'js_style' function that why nothing was happening when you clink on button.
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style()">Click on Me</button>
<script>
function js_style() {
//font styles added by JS:
document.getElementById("text").style.color = "purple";
document.getElementById("text").style.fontSize = "18pt";
document.getElementById("text").style.fontFamily = "Comic Sans MS";
document.getElementById("text").innerHTML = "Changed Text"; /* this
line should be here if you want to change the text of #text in you
html */
}
/* you were written this line here which out of the scope of
function */
</script>
</body>
</html>
Can you try:
<script type="text/javascript">
instead of just
<script>
?
try with onclick="js_style">:
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8 />
<title>Change Paragraph Text</title>
</head>
<body>
<p id ="text">I’m going to change this text, I hope.</p>
<button type="button" onclick="js_style">Click on Me</button>
<script>
function js_style() {
'use strict';
//font styles added by JS:
document.getElementById("text").style.color="purple";
document.getElementById("text").style.fontSize="18pt";
document.getElementById("text").style.fontFamily="Comic Sans MS";
}
document.getElementById("text").innerHTML = js_style();
</script>
</body>
</html>

is it possible to add class to a pseudo element?

I guess not as this is not working:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" >
$("p:after").addClass("allgone");
</script>
<style type="text/css">
p:after {
content: "daniel";
}
.allgone{
display: none;
}
</style>
<title></title>
</head>
<body>
<p></p>
</body>
</html>
JSFIDDLE
No, but you can add the class to the p element, and create an alternate style for it.
p:after {
content: "daniel";
}
p.allgone:after {
display: none;
}
$('p').addClass('allgone');
http://jsfiddle.net/xGUaY/
No, pseudo elements are not part of the DOM, and they can not be accessed via JavaScript.
I believe they are part of the Shadow DOM. The pseudo element is rendered by the browser as an inline element inside of the containing element, either as the first or last child.
No Since they are pseudo elements and not an actual DOM .
But you can do play with the class added, like say if you added the class box
then you can do .box:after and .box:before or .box::after and .box::before depending on the version you are coding.

Categories

Resources