JavaScript show and hide elements on click - javascript

Please excuse my ignorance, I have no idea what I'm doing, but I'm trying.
I attempted to figure it out by searching, but it has only yielded a functional result in jQuery. Since this is such a small section, I think it would be better to just use plain vanilla JavaScript instead of loading the entire jQuery library.
Does anyone know how/if I can accomplish the same functionality below, but with only normal JavaScript? Basically what I am trying to do is when "butt1" is clicked, the unordered list "links" will become hidden and the div "box1" will be shown:
<html>
<head>
<title>qwerty</title>
<style type="text/css">
.box1 {background: red;}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$("#butt1").live("click", show_box1);
function show_box1(event) {
$("#links").css("display", "none");
$(".box1").css("display", "inline");
}
</script>
</head>
<body>
<ul id="links">
<li id="butt1">blah</li>
<li id="butt2">blah</li>
<li id="butt3">blah</li>
</ul>
<div class="box1" style="display: none;">You clicked butt1!</div>
</body>
</html>
Here's a link to the above as a working example: http://jsbin.com/umitef/4/ -- this is the functionality I want replicated.
My extended thanks to anyone who takes a moment.. :-)

You can use getElementById to select an element using an id (equivalent to $("#something")), and getElementsByClassName to select elements based on class name (equivalent to $(".something")), and you can use the style property to set the display style (equivalent to the jQuery .css method):
var boxes = document.getElementsByClassName("box1");
document.getElementById("butt1").onclick = function() {
document.getElementById("links").style.display = "none";
for(var i = 0; i < boxes.length; i++) {
boxes[i].style.display = "inline";
}
}
Note however that getElementsByClassName is not supported in older versions of IE, which is why jQuery can be useful even for small things - it shortens the code and irons out all the annoying little browser differences.
Also, one major difference between the above code and your jQuery is the use of the .live jQuery method, which monitors the DOM and attaches the event to any element matching the selector, whether it was in the DOM already or it gets added in the future. With the above code, if there is not already an element with id "butt1" in the DOM when the code runs, you will get a TypeError, because getElementById will return null.

$("#links").css("display", "none");
Could become:
document.getElementById('links').style.display = 'none';
Realistically, loading jQuery makes a lot of sense since you're doing it from the Google CDN. A lot of sites use that so there is a good probability that at some point at least some of your users have already downloaded it. Plus, jQuery compressed is a very small download. So much so that the readability of jQuery style code is worth it.

Ok, while the easiest way is to do it jQuery style you can still replicate that functionality in Javascript.
The key here is the getElementById function to grab the specific element you want to manipulate and then you simply set the element.style.display property to 'none' when you want to hide it and 'block' or 'inline' when you want to show it (depending on the context)
Here is my crack at it...
<head>
<title>qwerty</title>
<style type="text/css">
#box1 {background: red;}
#box2 {background: blue;}
#box3 {background: yellow;}
</style>
<script type="text/javascript">
function toggle_visibility(id) {
var ul = document.getElementById('links');
var box = document.getElementById(id);
if(ul.style.display == 'none')
{
ul.style.display = 'block';
box.style.display = 'block';
}
else
{
ul.style.display = 'none';
box.style.display = 'block';
}
}
</script>
</head>
<body>
<ul id="links">
<li id="butt1">blah</li>
<li id="butt2">blah</li>
<li id="butt3">blah</li>
</ul>
<div id="box1" style="display: none;">You clicked butt1!</div>
<div id="box2" style="display: none;">You clicked butt2!</div>
<div id="box3" style="display: none;">You clicked butt3!</div>
</body>
</html>

this is asuming that you only have one box
window.onload = function() {
var links = document.getElementById("links"),
box1 = document.getElementsByClassName("box1")[0];
links.onclick = function() {
links.style.display = "none";
box1.style.display = "inline";
};
};

The production compressed version of Jquery is only 31KB. Load it through http://code.google.com/apis/libraries/devguide.html#jquery . You dont have to load the UI if you dont need it. The amount of code to do what you want isnt worth the ease in Jquery. Plus like JamWaffles said if there are other places that you will use Jquery then just load it and use it.

Related

Change style of multiple element groups simultaneously on hover using Angular

I find myself needing to change style of all elements that have an attribute in common (let's say a class name) when one of these elements is hovered. This is super easy to do with jQuery, like this:
$(function() {
$('.bookId4').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
Though I don't know how to achieve this with Angular. In this example, the elements that have the class .bookId4 are generated with Angular AJAX call, so I'd like to use Angular to create the hover effect as well. Thank you!
EDIT
To explain further, I will have many divs being generated with an AJAX call, and the div's that are in the same group will have the same class. This is the HTML code:
<div class="bookId{{ privateTour.booking.id }}"> <!-- Wrapper for hover effect -->
When one of the divs is hovered I want ALL of the divs (not only the div that is being hovered) with the same class (or some other value that they may have in common) to have a hover effect. My preferred way would be for Angular to search the whole page for all divs with a certain class name and apply a style to that class (to not have to for example generate tons of CSS for all the classes that were generated, which I'm not even sure it would work).
You can do that by using ng-mouseenter and ng-mouseleave directives, Here is the simple code, you can build on top of it to meet your requirements
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example73-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app="">
<h1 ng-style="myStyle" ng-mouseenter="myStyle={'background-color':'blue'}"" ng-mouseleave="myStyle={'background-color':'none'}"">Hello World</h1>
</body>
</html>
You can apply simple css solution for hover, like
.bookId4:hover {
background-color: '#F00';
}
No need for angular or jQuery :-)
Yes I agree with using ng-mouseenter and ng-mouseleave.
I did a example hope can help you
https://embed.plnkr.co/Cxfv0I9IEfBhZYj8A3zS/
use ng-class, create one scope variable which is by default false.
when mouseEnter OR mouseLeave event occurs make it TRUE/False accordingly.
<style>
.bookId4{color: red;}
</style>
<span ng-mouseenter="ctrl.hovered()" ng-mouseout="ctrl.nothovered()" ng-class="{ 'bookId4' : ctrl.ishovered==true }">soemthing 1</span>
<span ng-mouseenter="ctrl.hovered()" ng-mouseout="ctrl.nothovered()" ng-class="{ 'bookId4' : ctrl.ishovered==true }">soemthing 2</span>
<span ng-mouseenter="ctrl.hovered()" ng-mouseout="ctrl.nothovered()" ng-class="{ 'bookId4' : ctrl.ishovered==true }">soemthing 3</span>
_this.ishovered =false;
_this.hovered = function(){
_this.ishovered =true;
}
_this.nothovered = function(){
_this.ishovered =false;
}
In the end I found using an ng-class condition to be the best solution, and a variable decides what group should be highlighted. This line that I initially tried using did not work correctly:
<div ng-class="hovering == privateTour.booking.id ? 'hl' : ''" ng-mouseenter="hovering = privateTour.booking.id" ng-mouseleave="hovering = 0"> <!-- Wrapper for hover effect -->
For some reason, only the hovered div was highlighted, so I had to send the signal to a variable using a function instead for it to have a global effect. I ended up using this code for the div wrappers:
<div ng-class="hovering == privateTour.booking.id ? 'hl' : ''" ng-mouseenter="setHover(privateTour.booking.id)" ng-mouseleave="setHover(0)"> <!-- Wrapper for hover effect -->
And I wrote this simple function in the scope:
$scope.setHover = function(bookId) {
$scope.hovering = bookId;
};
And here's the style for the highlight class .hl:
.hl {
background-color: red;
}
Thank you for everyone giving the lead of ng-mouseenter and ng-mouseleave!

HTML displaying paragraph only when clicked

I would like to know how can I click on a text, and instead of linking to some external link, I would like to be able to display a paragraph on the same page.
For example, I want to have a hidden paragraph, and I want for it to be only be displayed when I click on some text.
I thought I can use "id", but I am not sure how!
<a id="tips">test</a>
Visit the Useful Tips Section
Any idea, how I can do this?
You don't necessarily Javascript. Your code is actually working, but you are not noticing it because both elements are one below the other. If you add a <div> with some height, you'll notice it.
Visit the Useful Tips Section
<div style="height: 1000px"></div>
<a id="tips">test</a>
(However, I don't mean you have to add this <div>).
you can use jquery to do it easily or if you want to avoid that, here is an alternate solution:
http://blog.movalog.com/a/javascript-toggle-visibility/
<script type="text/javascript"> <!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
} //--> </script>
Simply paste the above snippet of code underneath your tag and you call it by passing to it the ID of the element you wish to toggle the visibility of (this element can be anything that takes an id attribute). For example
<a href="#" onclick="toggle_visibility('foo');">
Click here to toggle visibility of element #foo</a> <div id="foo">This is foo</div>
or, in your case; include the function and:
<a id="tips" style="display:none;">test</a>
Visit the Useful Tips Section
Just takes some basic javascript code. This one right here is a good example. Comment if you want me to explain this in more detail.
<html>
<head>
<style type="text/css">
#text
{
display: none
}
</style>
<script type="text/javascript">
function callMe()
{
document.getElementById("text").style.display = 'block';
}
</script>
</head>
<body>
<div id="text">Hello! How are you?</div>
<form>
<input type="button" name="button" id="button" value= "Call Me" onclick="javascript:callMe()" />
</form>
<body>
</html>
Try add jquery and show the paragraph on click.
jsfiddle.net/6mk3a0ov/

Is there a way to ignore a class with the <noscript> tag?

I'm currently using wow.js in order to fade in content as you scroll down. The way it works is you add the div class wow to something you'd like to fade in, which the wow.js recognizes and then animates. (Really simple documentation here http://mynameismatthieu.com/WOW/docs.html)
However, if the browser has javascript disabled, it fails to recognize any css styling on anything with the class wow, as .wow is not defined in my stylesheet. I'm wondering if there is a workaround to this - should I add the .wow class to my own stylesheet as well, with something like .wow {display: block}? Or is there a way to tell a browser with no javascript enabled to simply ignore the wow class?
Unfortunately I cannot simply put a <noscript>message saying javascript is disabled, as I know many people at work will be viewing the site, where javascript is disabled, and they need to be able to view it.
The common way to do this is the other way around. I'm not sure if the library is limiting, but you can add a class to the <html> or <body> element identifying that JS is available. The way to do that in reverse would be to have a class like .no-js, and then remove it from the <body> if JS can run.
For example
<body class="no-js">
<script type="text/javascript">document.body.className = "";</script>
From there, in your CSS, simply do the following:
.no-js .wow {
display: block;
}
How about you only add the wow class if the browser does have Javascript?
For example:
<div id="one" class="wowable"></div>
<div id="two" class="wowable"></div>
<script type="text/javascript">
var wowables = document.getElementsByClassName('wowable');
for(var i = 0; i < wowables.length; i++) {
wowables[i].classList.remove( 'wowable' );
wowables[i].classList.add( 'wow' );
}
</script>

Hide/Show multiple times on a page

First of all, I know that this question has been answered on this site numerous times and that is the main problem here. I am spoiled for choice in the answers and have been searching for a few hours, not finding anything directly similar. There must be plenty of ways to do this, but what I have right now is closest to what I want.
I have this for my code at the moment, for some reason the fiddle won't work, while it works fine in my code, must have missed something.
http://jsfiddle.net/PVLMX/
Html:
<div id="wrap">
<p>This text is visible, but there is more.<br/><br/>See more >>
</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+'-show').style.display != 'none') {
document.getElementById(shID+'-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
}
else {
document.getElementById(shID+'-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
}
I need to be able to call the function for each new "Read More" on the page. At the moment, the first "See More" is always the target of the javascript, and I am not sure how to call this function for other links on the page.
In HTML, each id="" must be a unique identifier, you can't put two id="example" so you need id="example" and id="example2" and so on.
Working jsfiddle: http://jsfiddle.net/PVLMX/2/
<div id="wrap">
<p>This text is visible, but there is more.<a href="#" id="example2-show"
class="showLink" onclick="showHide('example2');return false;"><br/><br/>See more >></a>
</p>
<div id="example2" class="more">
<p>This text was hidden, now you see it</p>
<p><a href="#" id="example2-hide" class="hideLink"
onclick="showHide('example2');return false;">Hide this content >></a></p>
</div>
</div>
What I changed:
every id="example.. to id="example2... in the second div.
load the script in "No wrap - in head" mode (jsfiddle left option)
In your fiddle you need to select the no wrap in <head> option. Your code works fine.
http://jsfiddle.net/uND9H/
Aslo you can't have duplicate id's
if you want to generalise this, there is a much easier way in jquery ie by using class you can bind click events and generalise them using class names. Here is an example , Check it out
$('.showLink').bind('click',function(e){
var obj = $(this).attr('id');
var name = obj.replace("-show","-hidden");
$('#'+name).css('display', 'inline-block');
});
$('.hideLink').bind('click',function(e){
var obj = $(this).attr('id');
var name = obj.replace("-hide","-hidden");
$('#'+name).css('display', 'none');
});
http://jsfiddle.net/AmarnathRShenoy/AMf8y/
You can use class names multiple times and you must always remeber that id can never be duplicated
Actually you can do it with jquery and much easier than you think
Jquery as follows:
$more = $('.more');
$('.showLink').click(function(e){
e.preventDefault();
$more.show();
})
$('.hideLink').click(function(e){
e.preventDefault();
$more.hide();
})
Also add a css style to display:none on .more class.
you can make it look a little nicer with slideToggle()
Here is a fiddle: http://jsfiddle.net/up36g/

How to display JavaScript variables in a HTML page without document.write

I am trying to display some JavaScript variable on my HTML page.
I was first using document.write() but it use to overwrite the current page when the function was called.
After searching around, the general consensus was that document.write() isn't liked very much. What are the other options?
I found a page suggesting using .innerHTML but that was written in 2005.
A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/
Element.innerHTML is pretty much the way to go. Here are a few ways to use it:
HTML
<div class="results"></div>
JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
Full example. Click run snippet to try it out.
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);
// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');
$jqName.on('input', function(event){
$jqValue.html($jqName.val());
});
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting HTML content example</title>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
</body>
</html>
You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:
<div id="MyEdit">
This text will change
</div>
You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";​
Here is a working example
You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");
Here is a working example of the JQuery version
Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);
Here is the working version
Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.
there are different ways of doing this.
one way would be to write a script retrieving a command.
like so:
var name="kieran";
document.write=(name);
or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;
and the html code would be:
<p id="output"></p>
i hope this helped :)
You could use jquery to get hold of the html element that you want to load the value with.
Say for instance if your page looks something like this,
<div id="FirstDiv">
<div id="SecondDiv">
...
</div>
</div>
And if your javascript (I hope) looks something as simple as this,
function somefunction(){
var somevalue = "Data to be inserted";
$("#SecondDiv").text(somevalue);
}
I hope this is what you were looking for.
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
​var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);​​​​​​
innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";
Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
uploadElement.style.width = "100%";
hi here is a simple example: <div id="test">content</div> and
var test = 5;
document.getElementById('test').innerHTML = test;
and you can test it here : http://jsfiddle.net/SLbKX/
Add an element to your page (such as a div) and write to that div.
HTML:
<html>
<header>
<title>Page Title</title>
</header>
<body>
<div id="myDiv"></div>
</body>
</html>
jQuery:
$('#myDiv').text('hello world!');
javascript:
document.getElementById('myDiv').innerHTML = 'hello world!';
Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>

Categories

Resources