Hide DIV element with onclick command - javascript

Thanks to anyone who helps me solve this issue.
So the issue is I'm trying to hide an element (by class) with an onclick event using a button. But I am unable to do so.
Here's the code on jsfiddle http://jsfiddle.net/1tpdgrnj/
Here's the code for those who wish to help me here:
HTML:
<div class="box">Hide on button click!!
<button onclick="close();">Close</button>
Javascript:
function close() {
document.getElementsByClassName("box").style.display = 'none';}
UPDATE
Refer to the answer below and to the jsfiddle to see how it's different.

See this fiddle
Change your javascript as follows
function myFunction() {
document.getElementsByClassName("box")[0].style.display = 'none';
}
First change that should be done is, rename your function name, as close is a keyword in Javascript.
Second one is that, document.getElementsByClassName() returns an array and thus to get the first element you should use the index position 0.
According to the docs
The Element.getElementsByClassName() method returns a live
HTMLCollection containing all child elements which have all of the
given class names. When called on the document object, the complete
document is searched, including the root node.
Read more about it here

You can use Jquery
<div class="box">Hide on button click!!
<button class="close">Close</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".close").click(function(){
$(this).parent().hide(); return false;
});
});
</script>

Check this fiddle
You can also do this easily with jQuery.
$("#hide").click(function(){
$(".box").fadeOut(150);
});

Related

getElementsByClass and appendChild

just brushing up on my javascript skills and trying to figure out why getElementsByClass isn't working for my code. The code is pretty simple. Upon clicking a button "clicky", the script will create a child h1 element of div. It works perfectly fine when I use getElementById and changing the div class to Id but doesn't work when I change it to class.
I've tried, getElementsByClassName, getElementsByClass, getElementsByTagName and changing the div to the appropriate attribute but no luck.
<!doctype html>
<html>
<body>
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky </button>
<script>
function myFunction(){
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.getElementsByName("thistime").appendChild(first);
}
</script>
<div class="thistime">Hi</div>
</body>
</html>
You need to update your code from
document.getElementsByName("thistime").appendChild(first);
to
document.getElementsByClassName("thistime")[0].appendChild(first);
For reference - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Working code - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview
You could use getElementsByClassName(), which is supported in IE9+:
document.getElementsByClassName("thistime")[0].appendChild(first);
But a better alternative may be querySelector(), which is supported in IE8+
document.querySelector(".thistime").appendChild(first);
Note that querySelector() uses CSS selector syntax, so you should place a dot (.) before the class.
Snippet:
function myFunction() {
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.querySelector(".thistime").appendChild(first);
}
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky</button>
<div class="thistime">Hi</div>
As you have noticed, the function is called getElementsByName with "elements" being a plural.
It returns a list of markups by their name (and not their css class).
You need to use the function that handles the class name, and get the first element of the array, or loop on all the results, depending on what you are looking for.

Add class to div when clicked

I am trying to get a class to be added to a div element when clicked. I can not get it to work, I have it set up similar to this:
javascript:
function choose() {
this.addClass("selected");
}
html:
<div class="initialclass" onclick="choose()">CLICK</div>
I have other javascript commands in that function that are working properly I just can't get the class to add.
You have two issues with your current code. First is that this in your JS function refers to the window, not the element that was clicked. Second if it did refer to that element, it would be a DOMElement, not a jQuery object, so it would not have the addClass() method - you need to convert it to a jQuery object. Try this:
<div class="initialclass" onclick="choose(this)">CLICK</div>
function choose(el) {
$(el).addClass("selected");
}
Note however, that it is better practice to hook up your events using JavaScript. As you are using jQuery, you can do this:
<div class="initialclass">CLICK</div>
$(function() {
$('.initialclass').click(function() {
$(this).addClass("selected");
});
});
change your html like this:-
<div class="initialclass" onclick="choose(this)">CLICK</div>
and function:-
function choose(dv) {
$(dv).addClass("selected");
}
Use classList:
classList returns a token list of the class attribute of the element.
el.classList.add("selected");
classList.add:
Adds a class to an element's list of classes. If class already exists in the element's list of classes, it will not add the class again.
CODE
HTML:
<div class="initialclass" onclick="choose(this)">CLICK</div>
Javascript:
function choose(el) {
el.classList.add("selected");
}
DEMO
If you use jquery add this is code in your $(document).ready()
$(".initialclass").click(function(){
$(this).addClass("selected");
});

Using javascript on multiple Div Id's

I have created an expanding div that hides on load and expands when clicked using javascript and jQuery. My problem is that I need to use this feature multiple times on each page (10-30x). Is there a way to call the function to work with multiple Div ids using an array or something of that nature (I am a newbie, my apologies), e.g. a few of my div ids would be eb1, eb2, eb3, eb4. and here is my script that currently works on one id:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#eb1').hide();
//hides box at the begining
jQuery("#hide").click(function() {
jQuery('#eb1').fadeOut(300);
//jQuery('#the_box').hide();
});
jQuery("#show").click(function() {
jQuery('#eb1').fadeIn(300);
//jQuery('#the_box').show();
});
});
</script>
Any help would be appreciated, even a link to an explanation.
Thanks,
Travis
Further to John Conde's answer this is also possible using attribute-starts-with:
jQuery('div[id^="eb"]').hide();
JS Fiddle demo.
It is, of course, easier to just use a particular class-name, and the selector then becomes:
jQuery('.className').hide();
JS Fiddle demo.
References:
Attribute-starts-with ([attribute^="value"]) selector.
You should be able to do this by separating the ids with a comma:
jQuery('#eb1','#eb2','#eb3').hide();
just type "jquery multiple div show hide" into google:
the first link gives this:
Show/Hide Multiple Divs with Jquery
:)
Maybe it is cleaner to add a css class to all the div (or whatever tag you use) elements that should behave like that, then use that class in the selector ?
jQuery('div.hidable').hide();
//hides all 'hidable' boxes
jQuery("#hide").click(function() {
jQuery('div.hidable').fadeOut(300);
});
etc...
You could create a function to do that.
let me explain
function ToogleDiv(container){
// simple toogle
$(container).toggle();
// a toogle with some effect
$(container).toggle('slow', function() {
// add some action }); }
here's is a Jquery example Toogle Jquery Example
Hope this helps.
You can use Attribute Starts With Selector [name^="value"]
var divs = $('div[id^="eb"]');
$(divs).hide();
$('#show').click(function(){
$(divs).show();
});
$('#hide').click(function(){
$(divs).hide();
});
Live example on JSFiddle
function show(var id){
jQuery(id).fadeIn(300);
}
function hide(var id){
jQuery(id).fadeOut(300);
}
and then, in your divs:
<a id="hide" onClick="hide('eb1')">hide</a>
<a id="show" onClick="show('eb1')">show</a>
<div id="eb1"></div>

jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>
It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.
Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Check out the jQuery selectors and why not just use $(this)?
$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});
Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

Is there any way to use a JS variable as input instead of jquery selector "#id"?

I want to know that, can we able to give a variable instead of #anyId inside a selector.
Actually i am trying this code,
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="aDiv123">
<p id="abcd1234" class="abcd123">Click me!</p>
</div>
<script>
$("p").live("click", function() {
$(this).after("<p id='abcd123' class='abcd2323'>Another paragraph!</p>");
var number = this.id.match(/^abcd(\d+)$/)[1];
var iD = this.id;
alert(number);
alert(iD);
var div = "#"+"aDiv"+number;
alert(div)
$(div).remove();
});
</script>
</body>
</html>
This is the fiddle link for the above code.
Any suggestions about where i am doing it wrong!!!!
Thanks!
Yes you can use a variable, assuming it contains a string that is a valid jquery selector, or a reference to a DOM element, or a reference to another jquery object.
The jquery api documentation is excellent if you're getting stuck with jquery usage.
http://api.jquery.com/jQuery/
I believe your problem is just a typo. You have elements with IDs #aDiv123 and #abcd1234, but trying to remove #aDiv1234. Correct this and it will work.
The problem is that your Div has a different number from the paragraph, it should be:
<div id="aDiv1234">
<p id="abcd1234">
Not: aDiv123
The $ JQuery function only takes a string for parameter, so you can build your own selector passing by some variables.
var sel = tag + ':visible';
$(sel) -> all visible "tags"
If you want to do an operation on the div which contains the paragraph, why not instead do:
$('p').live('click', function() {
$(this).parent().remove();
});
... or ...
$('p').live('click', function() {
$(this).parents('.discriminator').remove();
});

Categories

Resources