I don't understand how to use document.getElementById(‘id’).onclick - javascript

I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.
I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.
If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.
Here is my code
<nav>
<button class="nav-button" id="nav">
<div class="menu-button"></div>
<div class="menu-button"></div>
<div class="menu-button"></div>
</button>
<div class="dropdown-menu" id="dropdown">
Hello
Hello
Hello
</div>
</nav>
.nav-button {
background: none;
border: none;
margin-left: 1em;
padding-top: 12px;
cursor: pointer;
}
.menu-button {
background-color: #fff;
width: 30px;
height: 4px;
margin-bottom: 5px;
border-radius: 5px;
}
.dropdown-menu {
margin-top: 7px;
width: 100px;
background-color: #fff;
display: none;
}
.showDropDown {
display: block;
}
function showDropDown() {
document.getElementById('dropdown').classList.toggle("showDropDown");
}
document.getElementById("nav").onclick = function showDropDown()
Here is a codepen
Thanks for your help!

just instead of
document.getElementById("nav").onclick = function showDropDown()
replace it with
document.getElementById("nav").onclick = showDropDown
because the onclick accepts function and you'r already defined this function

1.create myjavascript.js file in same folder where your page html is.
2.copy the javascript code in myjavascript.js "only code not tag <script></script>"
4.paste this at the end of your html page
<SCRIPT language="javascript" src="myjavascript.js" type="text/javascript"></SCRIPT>
This is the way to reference your code javascript in your html file.

It will be much easier to work with jquery than plain javascript.
Here how you are calling showDropDown function is wrong
change function showDropDown to
showDropDown
Better you can make the closure at the button click event like
let btn = document.getElementById("nav");
let toggleIt = document.getElementById('dropdown');
btn.onclick = function(){
toggleIt.classList.toggle("showDropDown");
};

Having it in a separate js file should work you just need to import the js file using the script tag. You should probably do this at the end of the HTML to guarantee that the js is ran after the DOM is loaded.
Update Your missing the brackets around the function call:
document.getElementById("nav").onclick = function() { showDropDown(); };

Related

Javascript "document" is not defined

I am studing javascript but console say's: document is not defined.
In this code:
var btnMenu = document.getElementById('btn-menu');
var nav = document.getElementById('nav');
btnMenu.addEventListener('click'), function(){
nav.classList.toggle('show');
})
I dont know what is wrong, can you help me?
I have tested your code in JsFiddle and you have a bug a parenthesis not needed after 'click'.
var btnMenu = document.getElementById('btn-menu');
var nav = document.getElementById('nav');
btnMenu.addEventListener('click', function(){
nav.classList.toggle('show');
})
.show {
width: 250px;
height: 100px;
background-color: red;
text-align: center;
font-size: 35px;
color: blue;
}
<div><input type ="submit" id="btn-menu" value="Menu Button"/>
<nav id="nav">The nav</nav>
</div>
So I have added html tags that refer to your code and also added some css code that needed to se the changes from the button when clicked.
Note. This is just an example how can you work with addEventListener and classList.toggle and making your piece of code working.

vanilla js remove id box [duplicate]

This question already has answers here:
Onclick event not firing on jsfiddle.net [closed]
(2 answers)
Closed 5 years ago.
I know how to do it with JQuery but I would like to remove a box with an onClick element (x) with vanilla JS. According to this I need to remove child element. As far as to this is my attempt:
function remove() {
var element = document.getElementById("box");
element.parentNode.removeChild(element);
}
#box {
background-color: lightgrey;
color: white;
width: 20em;
height: 20em;
border: 25px solid green;
padding: 25px;
margin: 25px;
}
.remover {
font-size: 10em;
align
}
<div id="box">
<div id="removeBox" onclick="remove()">
<span class="remover">x</span>
</div>
</div>
Would you mind to help me to remove whole box with just clicking the 'x'?
jsfiddle
Thank you so much
Don't use onclick, it's bad practice, here is why:
mixes code and markup
code written this way goes through eval
runs in the global scope while directly written functions run in user scope
Use event binding like:
document.getElementById("box").addEventListener('click', function() {
var element = document.getElementById("box");
element.parentNode.removeChild(element);
});
Here is an entire fiddle:
fiddle

Javascript - replace broken image by text (div; css class)

I am trying to replace all broken image by JS. I use this code to replace all broken images by notfound.png image.
$(document).ready(function() {
$('img').attr('onError', 'this.src="notfound.png"');
});
Anyway, I would like to replace them by a text notice instead of image. I cannot find the proper way how to do it, thank you very much for your help. JS is not my cup of coffee :(
I would like to use this for the text part:
Text to to shown...
EDIT:
OK, I have found this solution working fine, but doesnt accept CSS class
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>').addClass('error404');
});
});
</script>
Anyway as I wrote CSS class is not added, so this solution is not complete :(
CSS will be:
.error404 {
display: block;
color: #667d99;
font-weight: bold;
font-size: 11px;
border: 1px dotted;
border-radius: 3px;
padding: 5px;
margin: 10px;
background: #e7edf3;
text-aling: center;
}
Ok, I think I have found a solution for you. I tried to use jQuery error function. This one helped me:
To replace all the missing images with another, you can update the src attribute inside the callback passed to .error(). Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.
In your example this would be the best:
$('img').each(function() {
var img = $(this);
img.error(function() {
img.replaceWith('<div class="error404">Image not found (error 404)</div>');
}).attr('src', img.attr('src'));
});
I also made a jsFiddle example for you, which is working great for me.
You can create a text node and append it to the parent of img, and optionally remove img if needed. This code goes inside the error handler for img
$('img').on('error', function(){
$(this).parent().append($('<div>Broken image</div>'));
$(this).remove();
})
If you really need to use javascript for this try
$(document).ready(function() {
$('img').attr('alt', 'Alternative text');
});
But the same is achievable by barebone HTML
<img src="path/to/image.jpg" alt="Alternative text">
You can change the alt if an error is thrown just like you're doing with the image.
function imgMissing(image) {
image.onerror = "";
image.alt = "Image not Found";
return true;
}
The HTML:
<img src="image.jpg" onerror="imgMissing(this);" >
EDIT: OK, I have found this solution working fine:
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>');
});
});
</script>
Anyway one more think, I need to add CSS class "error404" for this "div", how to do that in JS? Thank you very much!
CSS will be:
.error404 {
display: block;
color: #667d99;
font-weight: bold;
font-size: 11px;
border: 1px dotted;
border-radius: 3px;
padding: 5px;
margin: 10px;
background: #e7edf3;
}

TypeScript Modal Window

I need to show a Modal in TypeScript. I don't want to use any library(bootstrap,..) to style it, I have to use own less styling for it. what I can use to Create a Modal? it can be a javascript modal that supported by typescript and by all browsers.
I tried to use showModal() like this:
This is my TypeScript Code:
function CreateModal() {
document.getElementById("myDialog").showModal();
}
It gave me this error - showModal is not exists.
even if It works it is not supported in IE and Firefix only works in chrome.
and this is my index.html
<script src="scripts/TypeScripts/Modal.js"></script>
<button onclick="CreateModal()">Show dialog</button>
<dialog id="myDialog">This is a dialog window</dialog>
I tried to use Onclick as well but it says does not existed.
span.onclick = function () {
modal.style.display = "none";
}
I know it's been a few months since this question was asked, but I recently had the same problem and was able to get a solution working.
In the typescript, you can ignore the need for the HTMLDialogElement by casting your dialog to type any.
openMyDialog() {
let myDialog:any = <any>document.getElementById("myDialog");
myDialog.showModal();
}
In your HTML, you just attached this function to the angular (click).
<button (click)="openMyDialog()">Open My Dialog</button>
The same technique can be used for the dialog's show() and close() functions.
If you're up for doing everything manually, you can place a partially transparent grey DIV over everything on the page, then a single DIV on top of it with your dialog. Toggle visibility with JS/CSS, and you're able to style any way you like it.
Here's a quick example, with a significant need for improved styling:
div.greyModal {
opacity: 0.7;
background-color: grey;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
div.modalContent {
opacity: 1;
position: fixed;
width: 75%;
left: 50%;
margin-left: -37.5%;
height:100px;
background-color: white;
border: solid 4px black;
border-color: black;
}
<div>
This is the web page content. <span style="color:red">This is red text that appears faded when the modalToggle divs are visible</span>
</div>
<div class="greyModal modalToggle">
</div>
<div class="modalContent modalToggle">
This is the content of my modal dialog
</div>

show/hide will not load

When clicking the "see more" the text does not expand. How come? Thanks
HTML:
<div id="wrap">
<h1>Show/Hide Content</h1>
<p>
This example shows you how to create a show/hide container using a
couple of links, a div, a few lines of CSS, and some JavaScript to
manipulate our CSS. Just click on the "see more" link at the end of
this paragraph to see the technique in action, and be sure to view the
source to see how it all works together.
<a href="#" id="example-show" class="showLink"
onclick="showHide('example');return false;">
See more.
</a>
</p>
<div id="example" class="more">
<p>
Congratulations! You've found the magic hidden text! Clicking the
link below will hide this content again.
</p>
<p>
<a href="#" id="example-hide" class="hideLink"
onclick="showHide('example');return false;">
Hide this content.
</a>
</p>
</div>
</div>​
Javascript:
function showHide(shID) {
if (document.getElementById(shID)) {
if (document.getElementById(shID).style.display != 'none') {
document.getElementById(shID).style.display = 'none';
}
else {
document.getElementById(shID).style.display = 'block';
}
}
}
CSS:
body {
font-size: 62.5%;
background-color: #777;
}
#wrap {
font: 1.3em/1.3 Arial, Helvetica, sans-serif;
width: 30em;
margin: 0 auto;
padding: 1em;
background-color: #fff;
}
h1 {
font-size: 200%;
}
/* This CSS is used for the Show/Hide functionality. */
.more {
display: none;
border-top: 1px solid #666;
border-bottom: 1px solid #666;
}
a.showLink, a.hideLink {
text-decoration: none;
color: #36f;
padding-left: 8px;
background: transparent url(down.gif) no-repeat left;
}
a.hideLink {
background: transparent url(up.gif) no-repeat left;
}
a.showLink:hover, a.hideLink:hover {
border-bottom: 1px dotted #36f;
}​
Live DEMO
You're calling showHide from the HTML window, but showHide hasn't been defined yet. Just include the showHide function in a <script> block in the HTML window, and it will work. See my jsfiddle: http://jsfiddle.net/HGbSX/1/
The additional problem with having to click twice to show the additional content has to do with your logic. The first time you come through, the display for that element is not set to none as you expect, but to an empty string, so it's re-hiding it. You can correct this by reversing your logic, and looking for display='block'. See my jsfiddle: http://jsfiddle.net/HGbSX/2/
I have corrected a small bug that it needs 2 clicks to start the functioning. Just replaced != 'none' has been replaced with == 'block'. Also, in JSFiddle, you had chosen wrong setting under the 'choose framework'. It should have been 'head no wrap'.
http://jsfiddle.net/EMEL6/12/
Also a very simple way to achieve the same:
function showHide() {
$('#example').toggle();
}
The code is correct; the reason it is not working is because the way you have the jsfiddle set up. On the right side where it asks for a framework/where you want your JS to show up, you have jQuery and onLoad (the defaults, I believe) - this makes it so that the resulting code of your fiddle looks like this:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
function showHide(shID) {
if (document.getElementById(shID)) {
if (document.getElementById(shID).style.display != 'none') {
document.getElementById(shID).style.display = 'none';
}
else {
document.getElementById(shID).style.display = 'block';
}
}
}
});//]]>
Which means you are defining showHide within the anonymous function of jQuery's load event. If you change the first dropdown to 'no wrap (head)' it will leave your JavaScript alone and your onclick will be able to see the function as defined.

Categories

Resources