Adding div dynamically using button click in JavaScript / jQuery - javascript

How do I dynamically add div on button click in JavaScript/jQuery?
I want all the formatting of div having class "listing listing_ad job".
This is my code which I tried out, using jQuery.
$('#btnAddtoList').click(function(){
var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
//newDiv.style.background = "#000";
document.body.appendChild(newDiv);
});
.listing {
border-bottom: 1px solid #ddd;
float: left;
padding: 0 0 5px;
position: relative;
width: 559px;
}
.listing:hover {
background: #f5f5f5 none repeat scroll 0 0;
border-bottom: 1px solid #ddd;
cursor: wait;
}
a:hover {
color: #ff5050;
}
.subtitle {
width: 430px;
font-weight: normal;
font-size: 12px;
font-family: Arial;
color: #7f7f7f;
}
.info {
float: left;
margin: 10px 15px 5px;
min-width: 500px;
clear: both;
color: #7f7f7f;
margin: 15px 44px 15px 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddtoList">
Add to list
</button>
<div class="listing listing_ad job">
<h4>
<a>
Excellent Opportunity For Internship at Diamond
</a>
</h4>
<div class="subtitle">
Lahore, Punjab
</div>
<div class="info">
This is Info / Description.
</div>
</div>
<!-- ************************ -->
<div class="listing listing_ad job">
<h4>
<!-- Src: http://jobs.mitula.pk/internship-program-lahore-jobs -->
<a>
Excellent Opportunity For Internship at Diamond
</a>
</h4>
<div class="subtitle">
Lahore, Punjab
</div>
<div class="info">
This is Info / Description.
</div>
</div>
Jsfiddle: http://jsfiddle.net/mr4rngbL/3/

Yes, you can - by added jQuery to the script of the document, and wrpping the code in document.ready
$(function() {
$('#btnAddtoList').click(function(){
var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
//newDiv.style.background = "#000";
$('body').append(newDiv);
});
});
Example http://jsfiddle.net/mr4rngbL/5/
Example for what you've asked in the comment: http://jsfiddle.net/mr4rngbL/6/
And LAST example based on your request in the comment: http://jsfiddle.net/mr4rngbL/7/

Here Pure JavaScript Solution
function addDiv(parent_div, content, attrs) {
var div = document.createElement('div');
var parent = document.getElementById(parent_div);
for (var key in attrs) {
if (attrs.hasOwnProperty(key)) {
div.setAttribute(key, attrs[key]);
}
}
div.innerHTML = content;
if (parent) {
parent.appendChild(div);
}
}
var button = document.getElementsByTagName('button')[0];
if (button) {
button.addEventListener('click', function() {
// change dynamically your new div
addDiv('parent', 'hi', {
'class': 'someclass someclass',
'data-attr': 'attr'
});
});
}
<button>Add Div</button>
<div id="parent">
</div>

Yes, you can easily add a div on button click in jQuery. First, set up the click listener:
$('button').on('click', addDiv);
Then, create the function to add the div (here, the div is being added to the element with the class of container):
function addDiv() {
$('.container').append('<div>').addClass('listing listing_ad job');
}
I hope this is helpful.

Related

Can I create actions based on HTML elements to show and hide divs with javascript?

Novice -
I am building a page in a TinyMCE wysiwyg and want to be able to show and hide divs when a link/button is clicked. The way things are structured, it appears I can't add javascript into the html section, so I am identifying the links with javascript.
From examples I was able to create the following code, which toggles a single div when clicking on any button marked with the toggleLink class. Is there a good way to target individual elements to show 1 div and hide the rest? I think getElementById might be heading in the right direction, but I am not sure how to apply the eventListeners individually
var togg = document.getElementsByClassName("toggleLink");
var i;
for (i = 0; i < togg.length; i++) {
togg[i].addEventListener("click", function() {
this.classList.toggle("active");
var openDiv = document.getElementById("myDIV1");
if (openDiv.style.display === "none"){
openDiv.style.display = "block";
} else {
openDiv.style.display = "none";
}
});
}
.demoLinks {
background-color: #fff;
height: 200px;
width: 15%;
font-size: 14pt;
color: #ffffff;
background-color: #3156f3;
padding: 20px 0px 20px 20px;
font-family: 'Lato', sans-serif;
float: left;
position: sticky; top: 100px;
}
.demoLinks p {
margin-bottom: 2px;
padding-left: 15px;
color: #ffffff;
}
.demoLinks p a {
color: #ffffff;
}
.toggleLink {
color: #ffffff;
cursor:pointer;
}
.demoVideos {
background-color: #fff;
width: 75%;
padding: 0px 0px 20px 20px;
font-family: 'Lato', sans-serif;
float: right;"
}
<div>
<div class="demoLinks">
<p style="margin-bottom: 8px; color: #ffffff; font-weight: bold;">Products:</p>
<p><a class="toggleLink">This Link</a></p>
<p><a class="toggleLink"> ThatLink</a></p>
</div>
<div class="demoVideos">
<div id="myDIV1" style="display: block;">
<p style="margin-bottom: 0.25em;"><span style="font-family: 'Lato', sans-serif; color: #2b28bc; margin-bottom: 0.5em;"><strong><span style="font-size: 24pt;">Product Demo 1</span></strong></span></p>
<div style="height:585px; width:1034px; background-color:#333333;"></div>
</div>
<div id="myDIV2" style="display: none;">
<p style="margin-bottom: 0.25em;"><span style="font-family: 'Lato', sans-serif; color: #2b28bc; margin-bottom: 0.5em;"><strong><span style="font-size: 24pt;">Product Demo 2</span></strong></span></p>
<div style="height:585px; width:1034px; background-color:#333333;"></div>
</div>
</div>
</div>
Thanks for any assistance!
You can correlate your links with your targets using a suffix on the 'id' property. So, for instance, you can give your first link an id of 'link1', which you can then relate to 'myDIV1' by replacing the text 'link' with 'myDIV'. And the same logic then for all link-div associations.
Once you have that, you should know that the function you pass to an event listener accepts a parameter which is the event that ultimately calls it. You can use this to get the id of the link that was clicked (e.target.id);
With that you can show the target div you're interested in, and hide the rest.
Below is a very simplified version of your code, along with my recommended logic. I should let you know that querySelectorAll has similar purposes to getElement(s)By..., but lets you select using css selectors. Also, the syntax 'test ? trueResult : falseResult' can be replaced by an if/then statement if you desire.
var links = document.querySelectorAll('.toggleLink');
var demos = document.querySelectorAll('.demoVideos > div');
for (var l = 0; l < links.length; l++) {
links[l].addEventListener("click", function(e) {
var linkDivId = e.target.id;
var targetDivId = linkDivId.replace('link', 'myDIV');
for (var d = 0; d < demos.length; d++)
demos[d].style.display = demos[d].id == targetDivId ? 'block' : 'none';
});
}
<div class="demoLinks">
<a id='link1' class="toggleLink">Demo 1 Link</a><br/>
<a id='link2' class="toggleLink">Demo 2 Link</a>
</div>
<br/>
<div class="demoVideos">
<div id="myDIV1" style="display: none;">
Product Demo 1
</div>
<div id="myDIV2" style="display: none;">
Product Demo 2
</div>
</div>
First off, forgive me a bit I took some liberties with your markup and CSS to make it easier for me to visualize the task at hand - toggle of visibility.
Rather than use an element id, I would suggest a class but here, I put in a data-linktarget on each of the links so you can simply put a selector in there and use either an id, class or whatever you choose which should give your task some flexibility.
Next, I used a hidden class to toggle the visibility of the target - this can be done several ways but I used this to help make intent clear. I also toggle the "active" class but did not do anything with it other than facilities what you had started.
Rather than a complex set of event handlers on multiple id's, I used a class to target the toggleLink class.
I made the code somewhat simple but enough to illustrate what it is doing.
function handleEvent(event) {
let videos = document.querySelector(".demo-videos");
let hideMe = videos.querySelectorAll(".demo-thing:not(.hidden)");
hideMe.forEach(function(el) {
el.classList.toggle("hidden", true);
el.classList.toggle("active", false);
});
let vSelected = videos.querySelector(this.dataset.linktarget);
vSelected.classList.toggle("hidden", false);
vSelected.classList.toggle("active", true);
}
Array.prototype.filter.call(document.getElementsByClassName("toggleLink"), function(testElement) {
testElement.addEventListener("click", handleEvent);
});
.hidden {
display: none;
}
.demo-container {
font-family: 'Lato', sans-serif;
}
.demoLinks {
height: 200px;
width: 15%;
font-size: 14pt;
background-color: #3156f3;
padding: 20px 0px 20px 20px;
float: left;
position: sticky;
top: 100px;
font-weight: bold;
}
.demo-links-title-text {
font-size: 1.2em;
color: #FFFF00;
}
.demoLinks .demo-link {
margin-bottom: 8px;
font-weight: bold;
margin-bottom: 2px;
padding-left: 15px;
}
.toggleLink {
color: #FFFF88;
cursor: pointer;
}
.demo-videos {
background-color: #fff;
width: 75%;
padding: 0px 0px 20px 20px;
float: right;
}
.demo-videos .header-part {
margin-bottom: 0.25em;
}
.demo-videos .header-part .header-part-text {
color: #2b28bc;
margin-bottom: 0.5em;
font-size: 24pt;
font-weight: bold;
/* put back <strong> tags if desired instead */
}
.demo-videos .block-part {
height: 585px;
width: 1034px;
background-color: #333333;
color: cyan;
}
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet">
<div class="demo-container">
<div class="demoLinks">
<p class="demo-links-title-text">Products:</p>
<p class="demo-link"><a class="toggleLink" data-linktarget="#myDIV1" href="#">This Link</a></p>
<p class="demo-link"><a class="toggleLink" data-linktarget=".demo-thing:nth-child(2)" href="#">ThatLink</a></p>
<p class="demo-link"><a class="toggleLink" data-linktarget=".demo-thing:nth-child(3)" href="#">That new Link</a></p>
</div>
<div class="demo-videos">
<div id="myDIV1" class="demo-thing active">
<p class="header-part"><span class="header-part-text"><span>Product Demo 1</span></span>
</p>
<div class="block-part">I am first</div>
</div>
<div id="myDIV2" class="demo-thing hidden">
<p class="header-part"><span class="header-part-text"><span>Product Demo 2</span></span>
</p>
<div class="block-part">Happy Day</div>
</div>
<div id="another-id" class="demo-thing hidden">
<p class="header-part"><span class="header-part-text"><span>Product Demo New</span></span>
</p>
<div class="block-part">Wonderful news</div>
</div>
</div>
</div>

JavaScript Accordion not working when i click on accordion heading text or chevron icon

I have built an accordion which I can add dynamically from an input and everything works fine except when I click on accordion heading text it doesn't work and also when I click on the chevron icon on the right side I get an error!! I am not sure why this happening. if I click on an empty space area it just works fine without any error. you can check the demo & code here on codepen -> https://codepen.io/tauhidul-islam/pen/eYZBzLY
Also here is some screenshot so you can understand. please let me understand what's happening and why. Thank you.
const addForm = document.querySelector(".add");
const list = document.querySelector(".section-list");
// Template Generator Function
const generateTemplate = (section) => {
let html = `
<div class="accordion">
<span>${section}</span>
<i class="fa fa-chevron-down"></i>
</div>
<div class="panel">
<span>Hey there you did it! :-)</span>
</div>
`;
list.innerHTML += html;
// accordion Selector
const accordion = document.querySelectorAll(".accordion");
// Show/Hide accordion Content on Click
for (i = 0; i < accordion.length; i++) {
accordion[i].addEventListener("click", (e) => {
let panel = e.target.nextElementSibling;
if (panel.classList.contains("panel")) {
panel.classList.toggle("active");
}
});
}
};
// Add Section
addForm.addEventListener("submit", (e) => {
e.preventDefault();
const section = addForm.add.value.trim();
if (section.length) {
generateTemplate(section);
addForm.reset();
}
});
.container {
width: 960px;
margin: auto;
}
.add-input {
padding: 15px;
border: 1px solid #dadada;
}
.add-btn {
background: white;
padding: 15px 25px;
margin-bottom: 10px;
border: 1px solid #dadada;
cursor: pointer;
}
/* Accordian Panel */
.accordion {
display: flex;
justify-content: space-between;
background: #03a9f4;
color: white;
padding: 15px;
box-shadow: 0px 0px 4px 0px #dadada;
cursor: pointer;
}
.panel {
display: none;
background-color: white;
padding: 15px;
}
.active {
display: block;
}
<div class="container">
<!-- Add Section -->
<form class="add">
<input type="text" name="add" class="add-input">
<button type="submit" class="add-btn">Add Section</button>
</form>
<!-- Section List -->
<div class="section-list"></div>
</div>
Because you are using e.target in the click event of the generated div, that will reference the template span when you click on the text and the div when you click on the blue bar, so .nextElementSibling won't always point to the same element. Instead, you want to always be calling .nextElementSibling on the div. This can be accomplished by using this.nextElementSibling, however because you are also using an arrow function, this binding won't correctly reference the element that received the event (the div), so if you change to using an anonymous function and this, it works.
const addForm = document.querySelector(".add");
const list = document.querySelector(".section-list");
// Template Generator Function
const generateTemplate = (section) => {
let html = `
<div class="accordion">
<span>${section}</span>
<i class="fa fa-chevron-down">^</i>
</div>
<div class="panel">
<span>Hey there you did it! :-)</span>
</div>
`;
list.innerHTML += html;
// accordion Selector
const accordion = document.querySelectorAll(".accordion");
// Show/Hide accordion Content on Click
for (i = 0; i < accordion.length; i++) {
// Use an anonymous function for the event listener so that
// "this" will bind to the element that recieved the event,
// which is the `div` in this case.
accordion[i].addEventListener("click", function(e) {
// We don't want to reference the element that triggered the event
// because that might be the span or the div and you won't always get
// the correct reference with .nextElementSibling. We always want to
// start from the div, which recieves the event.
let panel = this.nextElementSibling;
if (panel.classList.contains("panel")) {
panel.classList.toggle("active");
}
});
}
};
// Add Section
addForm.addEventListener("submit", (e) => {
e.preventDefault();
const section = addForm.add.value.trim();
if (section.length) {
generateTemplate(section);
addForm.reset();
}
});
.container {
width: 960px;
margin: auto;
}
.add-input {
padding: 15px;
border: 1px solid #dadada;
}
.add-btn {
background: white;
padding: 15px 25px;
margin-bottom: 10px;
border: 1px solid #dadada;
cursor: pointer;
}
/* Accordian Panel */
.accordion {
display: flex;
justify-content: space-between;
background: #03a9f4;
color: white;
padding: 15px;
box-shadow: 0px 0px 4px 0px #dadada;
cursor: pointer;
}
.panel {
display: none;
background-color: white;
padding: 15px;
}
.active {
display: block;
}
<div class="container">
<!-- Add Section -->
<form class="add">
<input type="text" name="add" class="add-input">
<button type="submit" class="add-btn">Add Section</button>
</form>
<!-- Section List -->
<div class="section-list"></div>
</div>
Without the loop for assigning the click handlers:
const addForm = document.querySelector(".add");
const list = document.querySelector(".section-list");
const expand = (element) => {
let panel = element.nextElementSibling;
if (panel.classList.contains("panel")) {
panel.classList.toggle("active");
}
};
// Template Generator Function
const getAccordionItem = (section) => {
let html = `
<div class="accordion" onclick="expand(this)">
<span>${section}</span>
<i class="fa fa-chevron-down"></i>
</div>
<div class="panel">
<span>Hey there you did it! :-)</span>
</div>
`;
return html;
};
// Add Section
addForm.addEventListener("submit", (e) => {
e.preventDefault();
const section = addForm.add.value.trim();
if (section.length) {
list.innerHTML += getAccordionItem(section);
addForm.reset();
}
});
body {
margin: 50px 0;
background-color: #f2f2f2;
font-family: Arial, Helvetica, sans-serif;
}
.container {
width: 960px;
margin: auto;
}
.add-input {
padding: 15px;
border: 1px solid #dadada;
}
.add-btn {
background: white;
padding: 15px 25px;
margin-bottom: 10px;
border: 1px solid #dadada;
cursor: pointer;
}
/* Accordian Panel */
.accordion {
display: flex;
justify-content: space-between;
background: #03a9f4;
color: white;
padding: 15px;
box-shadow: 0px 0px 4px 0px #dadada;
cursor: pointer;
}
.panel {
display: none;
background-color: white;
padding: 15px;
}
.active {
display: block;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Accordian</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<!-- Add Section -->
<form class="add">
<input type="text" name="add" class="add-input">
<button type="submit" class="add-btn">Add Section</button>
</form>
<!-- Section List -->
<div class="section-list"></div>
</div>
<script src="app.js"></script>
</body>
</html>

Hide and show DIV with javascript parameter

I am trying to do an event for hide and show with pure Javascript string parameters. I want to hide the other div once one of them is displayed (Let's say there are multiple div).
I tried to do it my own but I only managed to display once clicked. I had no idea how to hide the rest and only show that specified div.
Below is my code:
function show(id) {
if (document.getElementById('div_'+id).style.display == 'none') {
document.getElementById('div_'+id).style.display = 'block';
}
return false;
}
.title {
border:1px solid red;
display: inline-block;
font-size: 16px;
}
.content {
border: 1px solid blue;
display: inline-block;
font-size: 16px;
width: 300px;
}
<div class="title" onclick="show('first');">Title 1</div>
<div class="content" id="div_first" style="display:none;">Content 1
</div>
<div class="title" onclick="show('sec');">Title 2</div>
<div class="content" id="div_sec" style="display:none;">Content 2
</div>
You can use data-* attribute to store the target selector.
Don't use inline on* handlers. Keep your JS in one place.
Use CSS .is-active to manipulate the visibility state like display: block;
const showBtn = document.querySelectorAll('[data-show]');
const content = document.querySelectorAll('.content');
function show(ev) {
const selector = ev.currentTarget.getAttribute('data-show');
const elToShow = document.querySelectorAll(selector);
content.forEach(el => el.classList.remove('is-active'));
elToShow.forEach(el => el.classList.add('is-active'));
}
showBtn.forEach(el => el.addEventListener('click', show));
.title {
border:1px solid red;
display: inline-block;
font-size: 16px;
}
.content {
border: 1px solid blue;
display: inline-block;
font-size: 16px;
width: 300px;
display: none; /* ADD THIS */
}
.content.is-active{ /* ADD THIS */
display: block;
}
<div class="title" data-show="#content-1">Title 1</div>
<div class="title" data-show="#content-2">Title 2</div>
<div class="content" id="content-1">Content 1</div>
<div class="content" id="content-2">Content 2</div>
Just keep track of the id or element that is being displayed so that you can hide it if another one is selected. There's no need to iterate over them to hide them all, as you will know which one is being displayed, or to query the DOM each time to get the current one, as you can just keep a reference to it the first time.
I have updated the logic to toggle them if you click the same one twice and removed the inline event listeners, which I've moved to JS.
Note I have also replaced the <div>s for the .title elements with <button>s, as they will work better with keyboard navigation, mouse events and screen readers. You could also use <a>s instead.
let currentContentTab = null;
function show(e) {
// Using e.target you can get a reference to the clicked button:
const contentTab = document.getElementById(`div${ e.target.id.substring(3) }`);
const isHidden = contentTab.style.display === 'none';
// Toggle the panel we have just clicked (assuming you want to allow closing all of them again):
contentTab.style.display = isHidden ? 'block' : 'none';
// Hide the previous one, if any:
if (currentContentTab) {
currentContentTab.style.display = 'none';
}
// Keep track of the one we are currently displaying:
currentContentTab = isHidden ? contentTab : null;
}
// No need to have inline JS, you can bind the event listeners from JS:
for (const button of document.querySelectorAll('.title')) button.onclick = show;
body {
font-family: monospace;
font-size: 16px;
}
.title {
font-family: monospace;
font-size: 16px;
border: 1px solid red;
background: transparent;
padding: 8px;
outline: none;
}
.content {
border: 1px solid blue;
width: 300px;
padding: 8px;
margin-top: 8px;
}
<button class="title" id="tab1">Title 1</button>
<button class="title" id="tab2">Title 2</button>
<button class="title" id="tab3">Title 3</button>
<button class="title" id="tab4">Title 4</button>
<div class="content" id="div1" style="display:none; ">
Content 1...
</div>
<div class="content" id="div2" style="display:none; ">
Content 2...
</div>
<div class="content" id="div3" style="display:none; ">
Content 3...
</div>
<div class="content" id="div4" style="display:none; ">
Content 4...
</div>
If accessibility is important for you, you might want to add some ARIA attributes and the HTML hidden attribute:
let currentTab = null;
let currentPanel = null;
function show(e) {
const tab = e.target;
const id = tab.getAttribute('aria-controls');
const panel = document.getElementById(id);
// Toggle the panel we have just clicked:
tab.toggleAttribute('aria-selected');
panel.toggleAttribute('hidden');
// Hide the previous one, if any:
if (currentTab) {
currentTab.removeAttribute('aria-selected');
currentPanel.setAttribute('hidden', true);
}
// Keep track of the one we are currently displaying:
if (currentTab === tab) {
currentTab = null;
currentPanel = null;
} else {
currentTab = tab;
currentPanel = panel;
}
}
for (const button of document.querySelectorAll('.title')) button.onclick = show;
body {
font-family: monospace;
font-size: 16px;
}
.title {
font-family: monospace;
font-size: 16px;
border: 1px solid red;
background: transparent;
padding: 8px;
outline: none;
}
.content {
border: 1px solid blue;
width: 300px;
padding: 8px;
margin-top: 8px;
}
<button class="title" role="tab" aria-selected="true" aria-controls="div1" id="tab1">Title 1</button>
<button class="title" role="tab" aria-selected="true" aria-controls="div2" id="tab2">Title 2</button>
<button class="title" role="tab" aria-selected="true" aria-controls="div3" id="tab3">Title 3</button>
<button class="title" role="tab" aria-selected="true" aria-controls="div4" id="tab4">Title 4</button>
<div class="content" id="div1" role="tabpanel" aria-labelby aria-labelledby="tab1" hidden>
Content 1...
</div>
<div class="content" id="div2"role="tabpanel" aria-labelby aria-labelledby="tab2" hidden>
Content 2...
</div>
<div class="content" id="div3"role="tabpanel" aria-labelby aria-labelledby="tab3" hidden>
Content 3...
</div>
<div class="content" id="div4"role="tabpanel" aria-labelby aria-labelledby="tab4" hidden>
Content 4...
</div>
This JS code will grab all .content divs and will hide them unless it's the one we clicked.
function show(id) {
const el = document.getElementById('div' + id);
if (el.style.display == 'none') {
el.style.display = 'block';
}
const otherEls = document.querySelectorAll('.content');
otherEls.forEach(function (elItem) {
if (el !== elItem) {
elItem.style.display = 'none';
}
});
return false;
}
My solution as the following:
function show(id)
{
var divs=document.getElementsByClassName("content");
for (i=0;i<divs.length;i++)
{
divs[i].style.display='none';
}
document.getElementById('div_'+id).style.display = 'block';
}
.title {
border:1px solid red;
display: inline-block;
font-size: 16px;
}
.content {
border: 1px solid blue;
display: inline-block;
font-size: 16px;
width: 300px;
}
<div class="title" onclick="show('first');">Title 1</div>
<div class="content" id="div_first" style="display:none;">Content 1
</div>
<div class="title" onclick="show('sec');">Title 2</div>
<div class="content" id="div_sec" style="display:none;">Content 2
</div>

How to show/hide div click on image

I want to show/hide div when the user clicks on it. I found fiddle but it works on input, I want to integrate with Image. Please help me.
#content {
display: none;
}
input[type="text"]{
color: transparent;
text-shadow: 0 0 0 #000;
padding: 6px 12px;
width: 150px;
cursor: pointer;
}
input[type="text"]:focus{
outline: none;
}
input:focus + div#content {
display: block;
}
<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>
Just showing an image instead of the text should work.
<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
<img src="https://i.imgur.com/ZCbBNIt.png">
and the content will show.
</div>
See : JsFiddle
Try this
#content {
display: none;
}
img{
color: transparent;
text-shadow: 0 0 0 #000;
padding: 6px 12px;
width: 150px;
cursor: pointer;
}
img:focus{
outline: none;
}
img:focus + div#content {
display: block;
}
<img src='https://homepages.cae.wisc.edu/~ece533/images/airplane.png' tabindex="0"/>
<div id='content'>
and the content will show.
</div>
Try below code, I have created with jquery, it is working fine.
<img src='https://homepages.cae.wisc.edu/~ece533/images/airplane.png' tabindex="0" class="imgClick "/>
<div id='content'>
and the content will show.
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(e) {
$('.imgClick').click(function(){
$('#content').toggle();
});
});
</script>
This will do the job.
EDIT: I have attached the event listener on body instead of image, so that the event can be detected. You can make changes to optimize the code, as what I have given is very naive.
var isVisible = false;
function toggleDivDisplay(event) {
var contentDiv = document.getElementById("content");
if (isVisible) {
contentDiv.style.display = "none";
isVisible = !isVisible;
}
else if(event != undefined &&
'target' in event &&
event.target.id == "imgId") {
contentDiv.style.display = "block";
isVisible = !isVisible;
}
}
document.body.onclick = toggleDivDisplay;
#content {
display: none;
}
<img id="imgId" src="https://vignette.wikia.nocookie.net/marvelcinematicuniverse/images/3/35/IronMan-EndgameProfile.jpg/revision/latest/scale-to-width-down/2000?cb=20190423175213" height="50" width="50" onclick="toggleDivDisplay()">
<div id="content">
The content will show.
</div>

Reload CSS after toggling divs with JQuery

I've found a really clean simple way of toggling the visibility of divs with filters by Tim Robert-Fitzgerald on Codepen and it works great on my site however I need to extend it slightly for my needs.
By default I have an nth-child setup that removes the border of the second div, however when the divs are toggled this isn't reapplied to the second div. In reality it is still applied but this is not visible because the divs are set to display:none;
How can I get the nth-child to re-calculate once the divs have been toggled please?
var $btns = $('.btn').click(function() {
if (this.id == 'all') {
$('#parent > div').fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > div').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})
* {
box-sizing: border-box;
}
body {
padding: 10px;
background: #ecf0f1;
font-family: helvetica, sans-serif;
font-weight: 200;
}
.btn {
border: none;
background: linear-gradient(to bottom, #3498db, #2980b9);
border-radius: 3px;
font-family: Arial;
color: #ffffff;
padding: 5px 10px 5px 10px;
text-decoration: none;
margin: 5px;
}
.active {
background: linear-gradient(to bottom, #3cb0fd, #3498db);
text-decoration: none;
}
.box {
background:#2980b9;
padding: 10px;
height: 100px;
width: calc(33% - 10px);
float: left;
margin: 5px;
text-align: center;
border-radius: 3px;
color: #fff;
border:4px solid #000;
}
.box:nth-child(2) {
border:none;
}
.spacer {
clear: both;
height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="active btn" id="all">Show All</button>
<button class="btn" id="a">Show A</button>
<button class="btn" id="b">Show B</button>
<button class="btn" id="c">Show C</button>
<button class="btn" id="d">Show D</button>
<div class="spacer"></div>
<div id="parent">
<div class="box a b">A & B</div>
<div class="box a">A</div>
<div class="box b">B</div>
<div class="box c">C</div>
<div class="box d">D</div>
</div>
The CSS selector you used (:nth-child(2)) is not what you need because it's based on HTML DOM elements. The 2nd element never changes place in the DOM, it just gets hidden.
I don't believe there's a CSS solution to this but there is a jQuery solution.
I took your Codepen and modified very little things
CSS (instead of .box:nth-child(2))
.box.no-border {
border:none;
}
JS
var $btns = $('.btn').click(function() {
if (this.id == 'all') {
$('#parent > div').fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > div').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
$('.box').removeClass('no-border'); // reinitialize
$('.box:visible').eq(1).addClass('no-border'); // apply the class
})
Please note that the eq() method is 0 based index, so .eq(1) will get you the second element. Adding :visible will only get you those that are visible on screen.
This isn't working because the elements are still there, just hidden. You may want to consider using an additional class to control borders (or whatever other styles it is you are wanting) and swapping those with your jQuery the same way you are adding and removing the active class.

Categories