TBG basic structure

Hide & show content with javaScript

So, on my example I have 2 div-buttons (named btn1 and btn2) and 2 div elements (named content1 and content2). What I would want, is that when you click the btn1, content1 shows. If you click btn2, content2 should show. Content1 and content2 elements are currently placed in the same position, and by default, none of the content elements shouldn’t be open before you have clicked anything. I would like to achieve this with pure javaSript. Here is the example code:

var btn1 = document.getElementById("btn1"); var content1 = document.getElementById("content1"); content1.style.opacity = "0"; btn1.addEventListener("mouseover", showContent1); function showContent1() < if(content1.style.opacity === "0") < content1.style.opacity = "1"; >else > var btn2 = document.getElementById("btn2"); var content2 = document.getElementById("content2"); content2.style.opacity = "0"; btn2.addEventListener("mouseover", showContent2); function showContent2() < if(content2.style.opacity === "0") < content2.style.opacity = "1"; >else >
#btn1, #btn2 < width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px; >#contents < width: 200px;height:200px;border: 2px solid black; >#content1, #content2
show1
show2
content 1
content 2

Hey, uploaded the answer. I am not very experienced with javaScript, this was the best solution I could come up with, but it doesn’t work well.

Strange you put in question that you expect it to show on click, but inside the script you’re listening to mouseover event?

12 Answers 12

You can add click event to the buttons and based on the button clicked you can show or hide the respective div.

     #btn1, #btn2 < width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px; >#contents < width: 200px; height:200px; border: 2px solid black; >#content1, #content2   
show1
show2
content 1
content 2

Check this, i’ve made it dynamic so you can create unlimited buttons and contents.

#btn1, #btn2 < width:100px; height:20px; text-align:center; background:grey; cursor:pointer; margin:10px 0px; >#contents < width: 200px; height:200px; border: 2px solid black; >#content1, #content2
show1
show2
content 1
content 2

Whilst the above answers are all correct insofar as they will get you from A to B (based on the code you have provided), there are also a few ‘best practice’ changes you should use in your code, to avoid common pitfalls (and allow better maintainability and code reuse).

Читайте также:  JavaScript Yes/No Confirmation box

Firstly, you should avoid using IDs for styling. Whilst using an ID to apply styles is perfectly valid to do (and won’t break anything) it is discouraged. An ID for a page must always be unique within a document, so using it to style potentially multiple similar elements means that you will very quickly have either broken HTML (by reusing an ID) or unwieldy and non-maintainable stylesheets (by having multiple identical selectors). You should prefer using classes to add styles to elements, as you can reuse classes, and even extend or use multiple classes per element.

In my snippet, I have also used a dataset with a number in it to help identify which element is being ‘selected’. Datasets are intended to store custom data, and are extremely useful for storing and retrieving data in JavaScript. By using a dataset to store an ID that is independent of the ID or class of an element, you can infinitely add/remove tabs without having to change your CSS or JavaScript to fit. After all, I can add in a dataset for an ID of 3 (e.g. ) and the button styling won’t be affected.

Other good practices include using separate class names or selectors for JavaScript compared to those used to style an element (again so that you can change the name of a JavaScript selector without affecting the look of an element — you can also prepend a JavaScript selector with js- as I have done, so that it is more obvious that the selector is used by JavaScript, and not used to style an element).

I have also used a BEM styleguide to name my classes (though this is a preference thing — in short though, it is good practice to pick and then use some sort of naming convention or style guide for naming/styling elements).

A final recommendation (not shown) element instead of a for buttons. This will improve your disability access for a website, as screen reader technology can then distinguish between what is a button and what is merely a block of content (after all, a screen reader might not pick up that the has a click event handler added, and so a disabled user might not be aware they can click on the ‘button’ to switch tabs).

// Select all buttons using querySelectorAll let buttons = document.querySelectorAll('.js-toggle'); // Loop through each button and add an event listener Array.from(buttons).forEach(button => < // Click event listener button.addEventListener('click', function() < // Select all elements to hide/show let tab_contents = document.querySelectorAll('.js-content'); // Hide all elements hideElems(tab_contents); // Get ID of button let // Select relevant tab using the ID above document.querySelector(`.js-content-$`).style.display = 'block'; >); >); // Function for hiding all elements let hideElems = (elems) => < Array.from(elems).forEach(elem =>elem.style.display = 'none'); >
.button < width: 100px; height: 20px; text-align: center; background: grey; cursor: pointer; margin: 10px 0; >.tabs < width: 200px; height: 200px; border: 2px solid black; >.tabs__content
show1
show2
content 1
content 2

Источник

JavaScript hide and show content

I was searching for a pure CSS answer to hiding and showing content but after no luck I have been playing around with a piece of JavaScript code. My question is below the code, as it may help you to see the code first.

   
SERVICES

Loads of text blah blah blah

/* HIDE and SHOW content JavaScript function */ .hidden div .visible div .text_container < background-color: #39b54a; background-image: url("pattern2.png"); border: 1px solid #777777; box-shadow: 0 1px 1px inset, 0 0 40px rgba(0, 0, 0, 0.5) inset, 0 16px 0 rgba(255, 255, 255, 0.4) inset, 0 4px 5px rgba(0, 0, 0, 0.6); color: #000000; padding: 5px; text-align: left; width: auto; >.text_container h4 < cursor: pointer; >.text_container div p < margin-bottom: 10px; >.visible > div < display: block; font-size: 17px; height: 100%; >#rating > div < clear: left; height: 260px; >/* end of HIDE and SHOW content javascript function */

Currently as expected the div with area is clickable, so if a place a form in the child DIV when you select the form the content hides. I Would like to make only the H4 element clickable so clicking on the shown content will not hide the content. I am useless at JavaScript and I imagine this requires rejigging the js.

Источник

show/hide without framework

Ah, you added the new requirement indicating no inlines while I was posting my answer. I’ll update my answer with a solution that doesn’t use any inline javascript.

@galambalazs I can’t answer for Happy, but HTML is a display technology and really isn’t supposed to contain logic in it. Thus, JavaScript ideally shouldn’t be inlined in HTML. Browsers can handle inline JS just fine, it’s just that it goes against the display/semantic concept of HTML. Additionally, there might be technical constraints that prevent the use of inline HTML. That said, I’m generally OK with inlining simple JS instead of writing event listeners or using a framework.

5 Answers 5

look here to create a getElementByClass function — http://www.dustindiaz.com/getelementsbyclass/

then something like this (haven’t checked if it works, but you get the idea):

toggleItem = function() < var item = getElementByClass('toggle')[0]; if (item.style.display == "block") < item.style.display = 'none'; >else < item.style.display = 'block'; >> 

quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html this shows you a few functions to attach/detach eventhandlers cross-browser. attach the events when the page is loaded and you can avoid inline js.

I would create two methods that add/remove toggle class with native JavaScript:

function show(element) < element.className += " toggle"; >function hide(element) < element.className = (element.className).replace(/\s*toggle/g, ""); >

You will need code that places the onclick event on the span. Are you familiar with that?

@tvanfosson, this should not happen if you reliably use the show / hide . Nonetheless, I have updated the code as it is still a good idea. @Happy, it is not inline. Put this with your other JavaScript.

This uses an id on the hidden block to figure out which div to toggle. This is with the assumption that you want to toggle one block per clickable span. The event listener method is a W3C standard, but I’m not sure if IE implements it — do some testing to be sure.

JavaScript, goes in a script block in your HEAD or in a separate .js file:

window.addEventListener('load', init, false); function init() < document.getElementById('trigger').addEventListener( 'click', function() < targetId = this.getAttribute('rel'); var element = document.getElementById(targetId); if (element.style.display == 'block') element.style.display = 'none'; else element.style.display = 'block'; >, false ); > 

BTW, if you have multiple clickable spans, you could assign each span a class like «trigger». Then in the init() function, put the event listener registration in a loop that attaches the listener to everything that has a «trigger» class.

I’m sorry but css display can have much more values, than just 2: w3schools.com/css/pr_class_display.asp

Of course it doesn’t work in IE. sigh. Happy, if you look at the jQuery source code, you’ll probably find the code you need to accomplish your goal. If I recall, they had to put in some ugly hackish code to get this sort of thing working in IE. Frankly, you should just use inline JS or use a library like jQuery, which will let you do this without inline JS because they’ve taken care of doing all the, well, ugly hackish IE compatibility code for you.

First, there’s a function that will create a unique toggle function for whatever element you give it. Then, we wait for the window to load, and when it does, we create some toggle functions. In this example, we assume you have an element with , but you can use whatever you need to get an element. Then, we stick the toggle function into a global variable.

// returns a function that will toggle the given element function makeToggleFunction(el) < var element = el; return function() < if (element.style.display == 'none') element.style.display = 'block'; else element.style.display = 'none'; >; > window.addEventListener(‘load’, on_window_load, false); var GLOBAL = <>; function on_window_load()

You can then toggle the element whenever you need, with GLOBAL.toggle_element() .

Also, I think this is the code for IE if you want to wait for the page to load.

document.addEventListener("DOMContentLoaded", on_window_load, false);

Add this function (from http://www.dustindiaz.com/getelementsbyclass/ as mentioed by programatique)

function getElementsByClass(searchClass,node,tag) < var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) < if ( pattern.test(els[i].className) ) < classElements[j] = els[i]; j++; >> return classElements; >

And then add the following inside the function on_window_load :

GLOBAL.toggleable = new Array(); or each(var element in getElementsByClass('toggle')) < GLOBAL.toggleable.push(makeToggleFunction(element)); >GLOBAL.toggle_all = function() < for each(var f in GLOBAL.toggleable) < f.call(); >>;

And now you can call GLOBAL.toggle_all() and it will hide all elements that have the class toggle .

Источник

Javascript hide/show function

Im trying to create a login/register system/menu for a html5/js game im programming. At the moment i have set up the html page with the different divs ill be using for the menu.

LOAD/NEW

REGISTER

LOGIN

ACCESS

Please use a more up to date browser

:

:

Basically i want to use javascript/jquery to hide show the correct parts of the menu due to users decisions. So the first div the user will see is the access div which will give the user 2 options, «login» or «register» as you can see with the buttons within the access div above. Basically i want my JS to hide the access div when one of the buttons are pressed and then either show the login div or reg div depending on which button the user pressed. Here is the Js i have at the moment:

$(document).ready(function() < var loadScr = $("#load-new"); var regScr = $("#reg"); var loginScr = $("#login"); var accessScr = $("#access"); loadScr.hide(); regScr.hide(); loginScr.hide(); function login() < accessScr.hide(); loginScr.show(); >function register() < accessScr.hide(); regScr.show(); >>); 

It seems as though the onclick function of the buttons isnt interacting with the JS. i know this because i placed an alert which just said test in the login function which is called when the user clicks login button but i had no response back. Am i doing something rather silly? Thanks

Источник

Оцените статью