Toggle multiple Div names/content by one button click - html

i have 4 different divs in german. By clicking a button, i want to hide the german divs and instead show the english divs, which are hidden before.
There are ways to change between 2 divs, but how can i change mulitple divs at the same time by clicking one time on one button?

You'll need JavaScript
or for an easier approach a JavaScript library like jQuery.
The basic approach is to add data-* attributes and classes to your elements:
<button class="langButton" data-language="en">EN ARTICLES</button>
<button class="langButton" data-language="de">DE ARTICLES</button>
<button class="langButton" data-language="it">IT ARTICLES</button>
<div class="article en">En 1...</div>
<div class="article en">En 2...</div>
<div class="article de">De 1...</div>
<div class="article de">De 2...</div>
<div class="article it">It 1...</div>
<div class="article it">It 2...</div>
than your jQuery might look like:
$(function() { // Document is now ready to be manipulated
// Cache all .article elements
var $articles = $('.article');
$(".langButton").click(function(){
// Get the "en", "de" or "it" value
var language = $(this).attr("data-language");
// Hide all articles
$articles.hide();
// Show only the ones that have the ."language" related class
$("."+ language ).show();
});
});
Here's a live jsBin example you can play with or even download

Are you restricted to not use a framework like jQuery?
jQuery offers multiple methods to run your code on more than one selected elements.
Here is a basic working solution in pure javascript for you:
var shown = 'english';
function swap() {
if (shown === 'english') {
document.getElementById('german-1').style.display = "inline-block";
document.getElementById('german-2').style.display = "inline-block";
document.getElementById('german-3').style.display = "inline-block";
document.getElementById('english-1').style.display = "none";
document.getElementById('english-2').style.display = "none";
document.getElementById('english-3').style.display = "none";
shown = 'german';
} else {
document.getElementById('english-1').style.display = "inline-block";
document.getElementById('english-2').style.display = "inline-block";
document.getElementById('english-3').style.display = "inline-block";
document.getElementById('german-1').style.display = "none";
document.getElementById('german-2').style.display = "none";
document.getElementById('german-3').style.display = "none";
shown = 'english';
}
};
Link to jsfiddle:
https://jsfiddle.net/v2k3rzge/
Hope it helps

Related

HTML multiple pages on same file

i managed to do 2 pages on same file but when i try 3 with this same technique it doesn't work.
<script>
function show(shown, hidden, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
document.getElementById(hidden).style.display='none';
}
</script>
BMI-laskuri
Now this button shows content of Page 1 and 2 on same page but not the 3rd. I would like it to show only Page 2.
The pages are divs like this: (except page1 doest have display:none)
<div id="Page2" style="display:none">
I think the issue is that you have two parameters with the same name in your function which means when you refer to them it will only use the first instance of it.
If you change the names slightly, like I have below, I think you should be sorted.
function show(shown, hidden1, hidden2) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden1).style.display='none';
document.getElementById(hidden2).style.display='none';
}
I actually just created a site like this yesterday, and I've created many in the past (the most simple of them being this one: http://oops-studio.com/twinsremasteredobstaclecreator/helppage/)
How I usually do it is to just make every page a div which is a massive container for everything on the page, and then give it a class like page or something.
Then you can create a function like changePageTo(index) and have that loop through every page and set its style.display = "none"; then taking the target page and style.display = "block";
An example would be like so:
let pages = document.getElementsByClassName("page");
function changePageTo(index){
for(let i = 0;i < pages.length;i++){
pages[i].style.display = "none";
}
pages[index].style.display = "block";
}
You could also display pages using assigned names if you'd like, rather than indexes. How I would usually do that is just like so:
let pages = document.getElementsByClassName("page");
let pageNames = ["Cookies","Another page","The last page"];// One name per page element
function changePageTo(name){
let index = pageNames.indexOf(name);
if(index === -1){// If the page doesn't exist
// Do whatever you want in here
return;
}
for(let i = 0;i < pages.length;i++){
pages[i].style.display = "none";
}
pages[index].style.display = "block";
}
Hope this answers your question!
Here's a working example:
let pages = document.getElementsByClassName("page");
function changePageTo(index){
for(let i = 0;i < pages.length;i++){
pages[i].style.display = "none";
}
pages[index].style.display = "block";
}
changePageTo(0);
<div class = "page">
<h1>This is page one. It's titled "Cookies"</h1>
</div>
<div class = "page">
<h1>This is page two. It's titled "Another page"</h1>
</div>
<div class = "page">
<h1>This is page three. It's titled "The last page"</h1>
</div>
<button onclick = "changePageTo(0)">Show page 1</button>
<button onclick = "changePageTo(1)">Show page 2</button>
<button onclick = "changePageTo(2)">Show page 3</button>

When a user inputs x how do you make an x amount of input boxes appear?

I can't figure out how to do this in HTML, I'm new so i'd appreciate the help. What I want to do is this: when a user inputs x then an x amount of input boxes should appear(e.g. When they input 2 then 2 input boxes should appear)
The functionalities that you are looking for is possible with Javascript. Javascript is the programming language that is responsible for the logic in a web page (and many other places). So, you have to learn JS. But for now...
document.getElementById('button').addEventListener('click', function() {
let input = document.getElementById('some_id').value;
let container = document.getElementById('container');
container.innerHTML = "";
for (let i = 0; i < input; i++) {
let newInput = document.createElement('input');
container.appendChild(newInput);
}
});
<input id="some_id">
<button id="button">Create Me</button>
<div id="container"></div>
You can add the JS code in a separate file or add in at the end of your body tag inside a script tag

Toggle Text between multiple buttons

I would like to have two buttons which are basically categories. Let's name them category A and category B. The are displayed left and right. Below i would like to display some text which is dependent of the chosen category (i.e the clicked button) so that category A shows text A and category B shows text B.
This if for html. I'm working on a wordpress homepage.
I was able to install one button which toggles text (basically button 1 = Category A). But i couldn't manage to insert a second button (basically button 2 = Category B). Any ideas? Highly appreciated!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the button to swap the text of the DIV element:</p>
<p><button onclick="myFunction()">Click Me</button></p>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.innerHTML === "Hello") {
x.innerHTML = "Swapped text!";
} else {
x.innerHTML = "Hello";
}
}
</script>
</body>
</html>
I expect to have 2 buttons which display 2 categories, the text should toggle according to which button has been clicked.
Could put the description in an attribute, then get the attributes value on click and change the html of the description. Here is a jsFiddle
<div>
<button class="js-button default-button" data-description="Category A's Description" onclick="myFunction(this)">
Category A
</button>
<button class="js-button default-button" data-description="Category B's Description" onclick="myFunction(this)">
Category B
</button>
</div>
<div id="js-description" class="description">
</div>
<script>
function myFunction(elem) {
var x = document.getElementById("js-description");
var description = elem.getAttribute('data-description');
x.innerHTML = description;
var button = document.getElementsByClassName('js-button');
for (var i = 0; i < button.length; i++) {
button[i].classList.remove('active-button');
}
elem.classList.add('active-button');
}
</script>
<style>
.default-button{
font-size:16px;
border-radius: 4px;
padding:7px 12px;
}
.active-button{
background:blue;
color:#fff;
}
.description{
margin-top:20px;
}
</style>
I don't really like all these solutions because everything is written from JS but contents probably come from database. So here is my solution :
// Native JS version
// Working Fiddle : https://jsfiddle.net/d34cbtw7/
var togglers = document.querySelectorAll('[data-toggle="tab"]');
for (var i = 0; i < togglers.length; i++) {
togglers[i].addEventListener('click', function() {
var tabs = document.querySelectorAll('.tab');
for(var j = 0; j < tabs.length; j++) {
tabs[j].classList.remove('active');
}
var $target = document.querySelector(this.getAttribute('data-target'));
$target.classList.add('active');
});
}
// jQuery version
$('body').on('click', '[data-toggle="tab"]', function(e) {
e.preventDefault();
// Select our target
var $target = $($(this).data('target'));
// Hide all tabs
$('.tab-contents .tab').removeClass('active');
// Show only $target tab
$target.addClass('active');
});
.tab-contents .tab {
display: none;
}
.tab-contents .tab.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-toggle="tab" data-target="#cat-A-content">
Cat A
</button>
<button data-toggle="tab" data-target="#cat-B-content">
Cat B
</button>
<div class="tab-contents">
<div class="tab active" id="cat-A-content">
My category A contents
</div>
<div class="tab" id="cat-B-content">
My category B contents
</div>
</div>
I also don't really like "onclick" attribute in HTML...
I've made a quick codepen as example.
You can achieve this by passing a parameter to the onClick function. In this example I keep track of the last button clicked, and the text it should render. If the last button clicked was the same button, the switched back to default. I hope this helps.
https://codepen.io/maffekill/pen/rbpjzw
HTML
<p>Click the button to swap the text of the DIV element:</p>
<p><button onclick="myFunction(1, 'TEXT A')">TEXT A</button></p>
<p><button onclick="myFunction(2, 'TEXT B')">TEXT B</button></p>
<div id="myDIV">Default Text</div>
JS
// Keep track of the button currently clicked
var activeBtn = null;
function myFunction(btnId, text) {
var x = document.getElementById("myDIV");
// If the last button is the same as the new one, show default text
if (activeBtn === btnId) {
x.innerHTML = "Default Text";
activeBtn = null
} else {
// Else show the text given to the text param
x.innerHTML = text;
activeBtn = btnId;
}
}
There are multiple ways to achieve this, but the easiest way I could come up with to explain this to you would be as following:
function myFunction(myEle) {
var x = document.getElementById("myDIV");
x.innerHTML = "This is category " + myEle.value;
}
<p>Click the button to swap the text of the DIV element:</p>
<p>
<button onclick="myFunction(this)" value="a">
Category A
</button>
<button onclick="myFunction(this)" value="b">
Category B
</button>
</p>
<div id="myDIV">Hello</div>
JSFiddle
No need to overcomplicate things.
Firstly you would like to send the clicked element from the caller (which in this case would be the clicked element as well, the <button> element). You could use JavaScript's thisfor this purpose.
Within your function you can name a parameter between parenthesis, so in my example above: function myFunction() contains a parameter called myEle so it will look like: function myFunction(myEle). Once the function will be triggered, the parameter called myEle will be set to the clicked element (or
JavaScript's this). You can simply access any of its attributes like value by using a dot: myEle.value.
Knowing the above, you could apply it to whatever you require your function to do (refer to my example code above).

How can i change the innerHTML content when clicking on an image?

I'm quite new in coding, trying to educate myself because i'm interested. So, sorry if it's going to be a bit dumb question or not so specific or not really correct...
On my "practicing site" i'm having some navigation links, which are referring to different innerHTML contents (like different pages). I used the 'onClick' event to make them show up, for example like this:
<div class="nav" onClick="changeNavigation('a')">menu</div>
It works with texts perfectly, but my problem is that i don't know how to make the same with an image. So when i click on the image, i want to be redirected to that innerHTML page, like i did it with the text based button. I tried to do it like these two ways, but none of them worked.
<img src="picture.png" onClick="changeNavigation('a')" />
<div onClick="changeNavigation('a')"><img src="picture.png"></div>
Is it possible to make this with an image and the 'onClick' event? Or how else can i make this work?
By the way this is my script to make innerHTML show up:
<script>
function changeNavigation(id) {
document.getElementById('main').innerHTML = document.getElementById(id).innerHTML
}
</script>
I also tried to add my image an id that says 'main' like in the script this way, but with no result.
<img id="main" onClick="changeNavigation('f')" src="picture.png" />
Can you help me please? I would appreciate any answer, because i already searched about this and i didn't find anything that could've helped solve my problem and i'm really stuck right now.
(Sorry if my english isn't the best, it's not my native language.)
I have updated my answer to what you want. You need to the divs id you want to display as a parameter to the function you use for onclick. A sample is below.
var divs = ["Menu1", "Menu2", "Menu3", "Menu4"];
var visibleDivId = null;
function toggleVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.main_div{text-align:center; background: #00C492; padding:20px; width: 400px;}
.inner_div{background: #fff; margin-top:20px; height: 100px;}
.buttons a{font-size: 16px;}
.buttons a:hover{cursor:pointer; font-size: 16px;}
img {cursor:pointer}
<div class="main_div">
<div class="buttons">
<img src="http://www.clker.com/cliparts/J/g/2/D/p/I/one-hi.png" width="50px" onclick="toggleVisibility('Menu1');"> <img src="http://www.clker.com/cliparts/E/x/J/x/m/z/blue-number-two-hi.png" width="50px" onclick="toggleVisibility('Menu2');">
<img src="http://www.clker.com/cliparts/L/H/T/b/g/N/three-md.png" width="50px" onclick="toggleVisibility('Menu3');">
<img src="http://www.clker.com/cliparts/v/G/G/A/D/s/four-md.png" width="50px" onclick="toggleVisibility('Menu4');">
</div>
<div class="inner_div">
<div id="Menu1">I'm container one</div>
<div id="Menu2" style="display: none;">I'm container two</div>
<div id="Menu3" style="display: none;">I'm container three</div>
<div id="Menu4" style="display: none;">I'm container four</div>
</div>
</div>
You can just keep all of the sections as children of #main, and selectively show them when the section button in clicked. E.g.,
HTML
<nav>
<button type="button" data-index=0>Show one</button>
<button type="button" data-index=1>Show two</button>
<button type="button" data-index=2>Show three</button>
</nav>
<main id="main">
<section>One</section>
<section class="hidden">Two</section>
<section class="hidden">Three</section>
</main>
CSS
.hidden {
display: none;
}
JavaScript
const buttons = Array.from(document.querySelectorAll('button'));
const contentBlocks = Array.from(document.querySelectorAll('section'));
function hideSections (arr) {
arr.forEach(a => {
a.classList.add('hidden');
});
}
function showSection (index, sections) {
// Just a basic check, not exhaustive by any stretch
if (index !== undefined && sections !== undefined) {
hideSections(sections);
sections[index].classList.remove('hidden');
}
}
buttons.forEach(button => {
button.addEventListener('click', () => {
const contentBlocks = Array.from(document.querySelectorAll('section'));
const index = button.getAttribute('data-index');
showSection(index, contentBlocks);
});
});
Obviously you'll have to adjust your selectors for your use case, but Here's a pen
Here's a GitHub Gist pointing to some examples I created on JSFiddle based off of your specific use case (Stack Overflow doesn't let me post links to JSFiddle directly without including code here, but it's easier to follow along/experiment entirely in JSFiddle):
https://gist.github.com/andresn/f100386f06ee28e35bd83c62d9219890
More advanced stuff:
Ideally, you'd use what's called event delegation instead of adding an onclick to every anchor (DRY = Don't Repeat Yourself is good to always keep in mind while programming and so is KISS = Keep It Simple Silly). Here is a resource explaining event delegation:
https://davidwalsh.name/event-delegate
You can even take this further by preloading all your images so they load behind the scenes when the user first loads the page:
https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Toggle between two div couples when you click on them

I've found some Javascript code on the web for toggling between two images when clicking on them as in this example.
Now I wonder how to achieve the same result using divs with the pictures being inside the divs.
Both the small and the large image will each be the background image of a div which is inside another div that forms the border (I need to do this to be able to set the inner border radius of the image, which I can when I use an inner div and set its border radius). So I have:
<div class="bordersmallpicture"><div class="smallpicture"></div></div>
and
<div class="borderlargepicture"><div class="largepicture"></div></div>
How can I tell Javascript to toggle between those two div couples instead of images? Here is the Javascript code that I found for the images:
<script>
var imageURL = "small-picture.png";
if (document.images) {
var smallpicture = new Image();
smallpicture.src = "small-picture.png";
var largepicture = new Image();
largepicture.src = "large-picture.png";
}
function changeImage() {
if (document.images) {
if (imageURL == "large-picture.png") {imageURL = "small-picture.png";}
else {imageURL = "large-picture.png";}
document.myimage.src = imageURL;
}
}
</script>
And the HTML part:
<img src="small-picture.png" name="myimage" title="Click to resize" alt="tree">
Can anyone give me a hint how to edit this code to toggle between the div couples mentioned above? Or will a whole new code be necessary when dealing with divs?
You simply need to toggle the classes. See a running example using your images as CSS background in the classes:
<div id="border-div" class="bordersmallpicture">
<div id="image-div" class="smallpicture"></div>
</div>
The the Javascript becomes:
<script>
function changeImage() {
var currentClass = document.getElementById('border-div').className;
if(currentClass == 'borderlargepicture') {
document.getElementById('border-div').className = 'bordersmallpicture';
document.getElementById('image-div').className = 'smallpicture';
} else {
document.getElementById('border-div').className = 'borderlargepicture';
document.getElementById('image-div').className = 'largepicture';
}
}
</script>
If you expect using javascript a lot, I recommend using jQuery which would make the code easier:
<script>
function changeImage() {
$('#border-div').toggleClass('bordersmallpicture').toggleClass('borderlargepicture');
$('#image-div').toggleClass('smallpicture').toggleClass('largepicture');
}
</script>
toggleClass turns ON/OFF a class (Here is the example)