I am a total newbie. Can somebody tell me how to remove an HTML element using the original Javascript not jQuery.
index.html
<html>
<head>
<script type="text/javascript" src="myscripts.js" > </script>
<style>
#dummy {
min-width: 200px;
min-height: 200px;
max-width: 200px;
max-height: 200px;
background-color: #fff000;
}
</style>
</head>
<body>
<div id="dummy"></div>
<form>
<input type="submit" value="Remove DUMMY" onclick="removeDummy(); "/>
</form>
</body>
myscripts.js
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
}
What happens when I click the submit button, is that it will disappear for a very very short time and then appear back immediately. I want to completely remove the element when I click the button.
What's happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You're handling the click event on a submit button.
If you want to remove the element and not submit the form, handle the submit event on the form instead, and return false from your handler:
HTML:
<form onsubmit="return removeDummy(); ">
<input type="submit" value="Remove DUMMY"/>
</form>
JavaScript:
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
But you don't need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:
HTML:
<input type="button" value="Remove DUMMY" onclick="removeDummy()" />
JavaScript:
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZ attributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:
HTML:
<input id='btnRemoveDummy' type="button" value="Remove DUMMY"/>
JavaScript:
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
function pageInit() {
// Hook up the "remove dummy" button
var btn = document.getElementById('btnRemoveDummy');
if (btn.addEventListener) {
// DOM2 standard
btn.addEventListener('click', removeDummy, false);
}
else if (btn.attachEvent) {
// IE (IE9 finally supports the above, though)
btn.attachEvent('onclick', removeDummy);
}
else {
// Really old or non-standard browser, try DOM0
btn.onclick = removeDummy;
}
}
...then call pageInit(); from a script tag at the very end of your page body (just before the closing </body> tag), or from within the window load event, though that happens very late in the page load cycle and so usually isn't good for hooking up event handlers (it happens after all images have finally loaded, for instance).
Note that I've had to put in some handling to deal with browser differences. You'll probably want a function for hooking up events so you don't have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those browser differences for you. It's very important to understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit) to run as soon as the DOM is ready to be manipulated, long before window load fires.
Just do this
element.remove();
Try it here LOOK
http://jsfiddle.net/4WGRP/
You should use input type="button" instead of input type="submit".
<form>
<input type="button" value="Remove DUMMY" onclick="removeDummy(); "/>
</form>
Checkout Mozilla Developer Center for basic html and javascript resources
Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.
It reappears because your submit button reloads the page. The simplest way to prevent this behavior is to add a return false to the onclick like so:
<input type="submit" value="Remove DUMMY" onclick="removeDummy(); return false;" />
index.html
<input id="suby" type="submit" value="Remove DUMMY"/>
myscripts.js
document.addEventListener("DOMContentLoaded", {
//Do this AFTER elements are loaded
document.getElementById("suby").addEventListener("click", e => {
document.getElementById("dummy").remove()
})
})
Change the input type to "button". As T.J. and Pav said, the form is getting submitted. Your Javascript looks correct, and I commend you for trying it out the non-JQuery way :)
Try running this code in your script.
document.getElementById("dummy").remove();
And it will hopefully remove the element/button.
That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).
This works. Just remove the button from the "dummy" div if you want to keep the button.
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
#dummy {
min-width: 200px;
min-height: 200px;
max-width: 200px;
max-height: 200px;
background-color: #fff000;
}
<div id="dummy">
<button onclick="removeDummy()">Remove</button>
</div>
I'm still a newbie too, but here is one simple and easy way: You can use outerHTML, which is the whole tag, not just a portion:
EX: <tag id='me'>blahblahblah</tag>'s innerHTML would be blahblahblah, and outerHTML would be the whole thing, <tag id='me'>blahblahblah</tag>.
So, for the example, if you want to delete the tag, it's basically deleting its data, so if you change the outerHTML to an empty string, it's like deleting it.
<body>
<p id="myTag">This is going to get removed...</p>
<input type="button" onclick="javascript:
document.getElementById('myTag').outerHTML = '';//this makes the outerHTML (the whole tag, not what is inside it)
" value="Remove Praragraph">
</body>
Instead, if you want to just not display it, you can style it in JS using the visibility, opacity, and display properties.
document.getElementById('foo').style.visibility = hidden;
//or
document.getElementById('foo').style.opacity = 0;
//or
document.getElementById('foo').style.display = none;
Note that opacity makes the element still display, just you can't see it as much. Also, you can select text, copy, paste, and do everything you could normally do, even though it's invisible.Visibility fits your situation more, but it will leave a blank transparent space as big as the element it was applied to.I would recommend you do display, depending on how you make your webpage. Display basically deleting the element from your view, but you can still see it in DevTools.
Hope this helps!
Related
I have a script that adds a button that will open up a window that allows us to design t shirts. All i have top do is include their script and the button gets automatically added.
Below is the code which is dynamically added to the page.
<input id="design_edit_btn" class=" btn btn-success btn-block" value="Edit the design" type="button">
What i need to do is that, if that button is available then show a message saying its customizable or else display cannot be customized.
I tried the below code
if($("#design_edit_btn").length) {
alert("exists");
}
I did a bit of research but couldn't find a way to achieve this. Can someone please let me know how this can be done?
Thanks
You probably need to wait until the script has been loaded and executed.
Try waiting when the document is finished and do something like this:
jQuery(($) => {
if($("#design_edit_btn").length) {
alert("exists");
}
} );
jQuery triggers a given callback as soon as the document is ready. If that doesn't work either you could try adding a setTimeout as well.
Since the button you look for is create by an external script, that script is likely not finished by the time the DOM is ready, hence you won't find it, not even at $(document).ready()
What you can try is to use the script tag's onload, and when it fires, check for the button, like I do here, fire a console.log when jQuery have loaded.
Note, the order of the script is important
Stack snippet
<script>
function checkForjQuery() {
console.log('jQuery loaded');
}
function checkForButton() {
if ($("#design_edit_btn").length) {
alert("exists");
}
}
</script>
<script onload="checkForjQuery()" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- temp. commented out
<script onload="checkForButton()" src="your_script_path"></script>
-->
have you tried something like this:
if(document.getElementById('design_edit_btn') != null)
{
alert("exists");
}
This should do the trick
if ($("#design_edit_btn").length > 0) {
alert("exists");
}
More specifically, when I hover my cursor over a picture it would transform into a different picture. Or what I'm actually looking for: When I hover over text it would change into different text.
Thanks.
Yes, you would use the DOM events mouseenter and mouseleave. to change the image source.
Or you could use CSS :hover psuedo-class like this:
<div class="derp"></div>
.derp {
background-image:url(someURL);
}
.derp:hover {
background-image:url(someOtherURL);
}
Yes, it's easiest with the CSS :hover pseudo-elector.
#theimage {
display: block;
width: 400px;
height: 400px;
background: url('image1.png') 0 0 no-repeat;
}
#theimage:hover {
background: url('image2.png') 0 0 no-repeat
}
If you want to do things that are more complicated then you can use Javascript, which can use more complicated logic and access properties and attributes like the src of an image tag.
JSFiddle
You would also probably want to preload the image so that there is no delay the first time you hover (after clearing your cache). That's done best with Javascript:
<script>
(new Image).src = 'image2.png';
</script>
For changing text, you'll probably want to use JS. You could do something like this:
<script type=text/javascript>
function changetext()
{
var textchange2 = "new text" ;
var id = document.getElementById("ElementToChange");
id.innerHTML=textchange2;
}
function changetextback()
{
var textchange2 = "original text" ;
var id = document.getElementById("ElementToChange");
id.innerHTML=textchange2;
}
</script>
<div id="ElementToChange" onmouseover="changetext();" onmouseout="changetextback();">original text</div>
Yes, that is a standard function of Javascript to handle HTML DOM events. Using simple HTML/Javascript, you can attach an onmouseover event handler to run a Javascript function:
<html>
<head>
<script>
function changeText(obj){
// https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent
obj.textContent = "some new text";
// you could also use obj.innerHTML here, but
// that comes with security considerations
// https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
}
</script>
</head>
<body>
<div id="mydiv" onmouseover="changeText(this)">Some text</div>
</body>
</html>
There are convenience functions in Javascript frameworks like jQuery as well:
$(obj).text('Some new text from jQuery');
Note that you need to include the jQuery library in your <head> block to use it.
Attaching event handlers to DOM events via inline properties like onmouseover may result in harder to manage code over the long run. Attaching event listeners via code is better:
<html>
<head>
<script>
function changeText(event){
// the Event object - here called event as a variable name
// is passed implicitly
event.target.textContent = "some new text";
}
window.onload = function(){
document.getElementById("mydiv")
.addEventListener("mouseover", changeText, false );
}
</script>
</head>
<body>
<div id="mydiv">Some text</div>
</body>
</html>
jQuery makes it easy:
$(document).ready(function() {
$("#mydiv")
.on( "mouseover", function(event){
$(event.target).text('some new text');
});
});
I suggest you Google Javascript tutorials and go through an HTML/Javascript beginner's tutorial. Mozilla Developer Network is a good place to start learning:
https://developer.mozilla.org/en-US/
If you really get interested in it, check out NodeJS for server-side Javascript:
http://nodejs.org/
Can I use exactly the same code to handle clicks for static and for Ajax-generated buttons? The reason I ask is that I can't get a click handler to work for an Ajax button, but if I write the equivalent static HTML, the click does work.
This code is the static version, which does work:
// in JS file:
$(function(){
$('input.sButton').click(function(){
var f = $.farbtastic('#picker');
f.linkTo(this);
return false;
});
});
In the "static HTML":
<div id = "inputArea">
<label style="white-space: nowrap; line-height: 14px; height: 14px; vertical-align: bottom;">
<input id="sButton1" class="sButton" type="button" style="background-color: rgb(113, 16, 232);">
fubar1
</label>
</div>
The normal "dynamic HTML" looks like this:
<div id = "inputArea">
</div>
The Ajax code loads the buttons into 'inputArea'. I derived the static version of this code from Firebug. I ran the Ajax routine, then got the HTML view in Firebug, which included the server output, and cut-and-pasted it exactly into my static test code, which is reproduced above. In other words, I know that the static and dynamic HTML are equivalent.
But - the static code works, and the dynamic one doesn't. Firebug shows the JS click handler being entered for the static version, and the farbtastic colour picker pops up, but this doesn't happen in the dynamic code. Any ideas?
If you are using jquery 1.7+, use on instead of click
http://api.jquery.com/on/
$("body").on("click","input.sButton",function(){
//do whatever you want
});
if you use a lower version of jquery, use live
$('input.sButton').live("click",function(){
//do whatever you want
});
$('input.sButton').live('click', function(){
var f = $.farbtastic('#picker');
f.linkTo(this);
return false;
});
.live listens even for ajax content. Thsi should do the trick. Also, you may want to look into jquery .on() as well. Make sure you're using the latest jquery.
there is a jQuery live function just for that purpose, check out it here
Hey, I'm using a html form that is used to log people into my website, I am building it so it uses AJAX (jQuery) but I'm having some problems.
Here is the JavaScript:
function validateLoginDetails() {
$('[name=loginUser]').click(function() {
$("#mainWrap").css({ width:"600px", height:"200px" });
$("#interfaceScreen").load("modules/web/loginForm.php?username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
});
}
Here is the html form:
<form id="formLogin" name="loginUser" method="post">
Username<br /><input id="username" name="username" type="text" maxlength="30" style="width:160px; border:solid 1px #444444;" /><br /><br />
Password<br /><input id="password" name="password" type="password" maxlength="50" style="width:160px; border:solid 1px #444444;" /><br /><br />
<input id="submit" type="submit" value="Play" style="width:100px; background:#FFFFFF; border:solid 1px #444444;" />
</form>
The problem is, when I submit the form it runs the code but then goes back to how it was before, this may sound weird but I can tell because I can see it changing the div size and then right after reverting back to its original size.
Any ideas?
EDIT: If I run the code with the below link for example then it works fine.
Clicky
You need to return false from your handler so that it doesn't perform the actual form post after doing the AJAX call.
Here's what I would do.
$(function() {
$('#formLogin').submit( function() {
$('#mainWrap').css( { width: '600px', height: '200px' });
$.post( 'modules/web/loginForm.php',
$(this).serialize(),
function(data) {
$('#interfaceScreen').html(data);
}
);
return false;
});
});
Note that I'm using a post to make sure that the URL (including the username and password) doesn't end up exposed in the web logs. I'm also assuming that the page containing the form was loaded via https and, thus, the post will be secured as well.
I'm pretty sure tvanfosson is on the right path. Try moving up the return false into the click function or try canceling the event.
$('[name=loginUser]').click(function() {
//do stuff
return false;
});
or
$('[name=loginUser]').click(function(e) {
e.cancel();
});
If you're dealing with a form submission, you should really opt for the .form() event handler, rather than a .click() event handler. With the former, if the form is submitted via any other methods, your checks will still run, whereas click depends on that one single element firing an action. You'll also need to return false or preventDefault() on this event, so your function actually fires correctly.
The other thing (and this may be minuscule/unimportant based on the code sampling you've provided) is that you're binding that event handler in a function that has to be called - why not load it on document ready, like so (see below)?
I'd rework your code like this, personally:
$(document).ready(function() {
$('#formLogin').submit(function() {
$("#mainWrap").css({ width:"600px", height:"200px" });
$("#interfaceScreen").load("modules/web/loginForm.php?username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
return false;
});
});
First, did you confirm that your .php file is returning content and not an error? If you are inserting content (with $load), you should not trigger the CSS commands on the div until your expected content (from load) has returned successfully e.g. use callback. Also, I would suggest using .submit(), a form specific function, with a direct reference to the form tag and/or id to speed things up (not making jquery search as many things in the DOM).
< style >
.loadReg{ width:[yourBeginWidth]; height:[yourBeginHeight];}
.loadSuccess{ width:600px; height:200px;}
< / style >
function validateLoginDetails() {
$('#formLogin').submit(function() {
// using load(url,{data:toPOST},callback(if successful));
$("#interfaceScreen").load("modules/web/loginForm.php?",
{"username": encodeURIComponent(username), "password": encodeURIComponent(password)},
function(){$("#mainWrap").toggleClass('loadSuccess');}
);// end load
});// end submit
return false;
}
This could be even more efficient and less obtrusive, but wanted to leave it recognizable. The other guys are right...if your Div is returning to its original size...it is because the page is being allowed to reload...in which case your initial DIV width/height are applied by the browser...as your alternate width/height are only applied by jquery onsubmit.
To recap:
assign submit event to form directly
use $load built-in ability to pass the value pairs is object {name:val}
move CSS to unobtrusive state vs buried in code
trigger CSS if successful
stop page from reloading and resetting display
I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <head>
note: I am working with a local server, so pageload in instant.
function changeVisibility() {
var a = document.getElementById('invisible');
a.style.display = 'block';
}
var changed = document.getElementById('click1');
changed.onchange = changeVisibility;
This here is the corresponding HTML
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.
Problem is, I keep getting this error:
"changed is null:
changed.onchange = changeVisibility;"
i don't get it, I seriously don't get what I'm overlooking here.
EDIT: question answered, thank you Mercutio for your help and everyone else too of course.
Final code:
function loadEvents() {
var changed = document.getElementById('click1');
var a = document.getElementById('invisible');
document.getElementById('addField').onclick = addFileInput;
changed.onchange = function() {
a.style.display = 'block';
}
}
if (document.getElementById) window.onload = loadEvents;
This here is the corresponding HTML:
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
Also, thanks for the link to JSbin, didn't know about that, looks nifty.
This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
note: I am working with a local server, so pageload in instant.
that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D
The onlything I'd like to do now is remove the Javascript link from the ...
Place an id on there, and inside your function do this:
document.getElementById('addField').onclick = addFileInput;
Or, as you already have the div as the variable 'a':
a.firstChild.onclick = addFileInput;
But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.
mercutio is correct. If that code is executing in the HEAD, the call to "document.getElementById('click1')" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler.
I think its because you are trying to modify a file element.
Browsers don't usually let you do that. If you want to show or hide them, place them inside of a div and show or hide that.
Right, I've modified things based on your collective sudgestions and it works now. Onlything bothering me is the direct reference to Javascript inside the anchor
You need to wrap your code in a window.onload event handler, a domReady event handler (available in most modern js frameworks and libraries) or place at the bottom of the page.
Placing at the bottom of the page works fine, as you can see here.
Decoupling event responder from your markup is covered under the topic of "Unobtrusive JavaScript" and can be handled in a variety of ways. In general, you want to declare event responders in a window.onload or document.ready event.