I am beginning with JavaScript and I have a following problem. My webpage by default shows content of all <li> that is Journal Articles, Working papers and Conferences. I would like to have selected the first <li> when I come to the website, that is in this case journal Articles.
Relevant part of the HTML code:
<div class="row" data-aos="fade-up">
<div class="col-lg-12 d-flex justify-content-center">
<ul id="portfolio-flters">
<li data-filter=".filter-journal">Journal articles</li>
<li data-filter=".filter-wp">Working papers</li>
<li data-filter=".filter-conferences">Conferences</li>
</ul>
</div>
</div>
<div class="row portfolio-container" data-aos="fade-up" data-aos-delay="100">
<div class="col-lg-4 col-md-6 portfolio-item filter-journal">
Articles published in journals with IF.
</div>
<div class="col-lg-4 col-md-6 portfolio-item filter-wp">
<li>Misak, V. (2022). Crime and weather: Evidence from the Czech Republic (No. 9/2022). IES Working Paper.</li>
<br>
<li>Garcia-Bernardo, J., Jansky, P., & Misak, V. (2021). Common Agricultural Policy Beneficiaries: Evidence of Inequality from a New Data Set (No. 4/2021). IES Working Paper.</li>
</div>
<div class="col-lg-4 col-md-6 portfolio-item filter-conferences">
<u> 2022: </u>
<li>Young Economists Meeting, Brno, Czech Republic</li>
<li>MAER-Net Colloquium, Kyoto, Japan</li>
</div>
</div>
Javascript function:
window.addEventListener('load', () => {
let portfolioContainer = select('.portfolio-container');
if (portfolioContainer) {
let portfolioIsotope = new Isotope(portfolioContainer, {
itemSelector: '.portfolio-item'
});
let portfolioFilters = select('#portfolio-flters li', true);
on('click', '#portfolio-flters li', function(e) {
e.preventDefault();
portfolioFilters.forEach(function(el) {
el.classList.remove('filter-active');
});
this.classList.add('filter-active');
portfolioIsotope.arrange({
filter: this.getAttribute('data-filter')
});
portfolioIsotope.on('arrangeComplete', function() {
AOS.refresh()
});
}, true);
}
});
How can I modify my JavaScript function to select the first child of by default, please?
Desired output is this:
You code was a bit hard to work with because all the classes are missing and the indents didn't format properly in your question.
I wrote below a full example for how you can achieve the tabs effect your going for below. Hope it helps! I tried to keep it simple and add comments. LMK if you have any questions :)
let currentTab = 0;
let tabItems = document.querySelectorAll('.tabItem');
let tabContents = document.querySelectorAll('.tabContent');
function updateTabs() {
// CYCLE THROUGH EACH tabItems
for (let i = 0; i < tabItems.length; i++) {
tabItems[i].className = i == currentTab ? 'tabItem tabItemSelected' : 'tabItem'; // SET TAB WITH INDEX currentTab TO INCLUDE tabItemSelected CLASS
tabContents[i].style.display = i == currentTab ? 'block' : 'none'; // ONLY SHOW THE CONTENT THAT CORRESPONDS TO INDEX currentTab
}
}
updateTabs(); // LOAD TO STATE 0 --> YOU CAN DO THIS IS document.onload for example
for (let i = 0; i < tabItems.length; i++) {
let curI = i; // CACHE i LOCALLY
tabItems[i].onclick = function() {
currentTab = curI;
updateTabs(); // UPDATE TABS ON CLICK...
}
}
.tabContainer {
width: 100%;
height: 50px;
border-bottom: 1px solid gray;
background-color: #ccc;
}
.tabItem {
display: inline-block;
width: 33.33%;
height: 50px;
line-height: 50px;
text-align: center;
cursor: pointer;
}
.tabItemSelected {
color: blue;
border-bottom: 2px solid blue;
}
<div class="tabContainer">
<div class="tabItem">TAB A</div><div class="tabItem">TAB B</div><div class="tabItem">TAB C</div>
</div>
<br><br>
<div class="tabContent" style="color: red">
Content A
</div>
<div class="tabContent" style="color: blue">
Content B
</div>
<div class="tabContent" style="color: green">
Content C
</div>
Related
I have a page that contain different section these section appear when the user click on li an active class is added to the section and then this section appear
each section contain a box with checkboxes and a link to another page when i click on this link i should store the value of the checkboxes for the section active only to print them later
all the code work fine but my problem is that i only can have the checkbox value for the first section that contain active class by defaul
how can i solve that please?
/*Put active class on li click for section*/
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
let section = document.querySelectorAll(".section");
let sectionArray = Array.from(section);
tabsArray.forEach((ele) => {
ele.addEventListener("click", function (e) {
tabsArray.forEach((ele) => {
ele.classList.remove("active");
});
e.currentTarget.classList.add("active");
sectionArray.forEach((sec) => {
sec.classList.remove("active");
});
document.querySelector('#' + e.currentTarget.dataset.cont).classList.add("active");
});
});
/*put the check box value in localstorage to print them later*/
let printBtn = document.querySelector(".active .btn-print");
let terms = document.querySelectorAll(".active input[type='checkbox']");
let termsValChecked = [];
let termsValUnChecked = [];
printBtn.addEventListener("click", function (e) {
localStorage.removeItem("termschecked");
localStorage.removeItem("termsunchecked");
for (let i = 0; i < terms.length; i++) {
if (terms[i].checked == true) {
termsValChecked.push(terms[i].value);
} else {
termsValUnChecked.push(terms[i].value);
}
}
window.localStorage.setItem("termschecked", JSON.stringify(termsValChecked));
window.localStorage.setItem("termsunchecked", JSON.stringify(termsValUnChecked));
});
.box {
display: flex;
align-items: center;
}
section {
display: none;
}
section.active {
display: block;
}
.nav {
list-style:none;
display: flex;
align-items: center;
}
.nav li {
padding: 20px;
background-color: #ccc;
margin-left: 2px;
cursor: pointer;
}
<ul class="nav">
<li data-cont="r1">1</li>
<li data-cont="r2">2</li>
<li data-cont="r3">3</li>
</ul>
<section class="section section-one active" id="r1">
<h3>Section 1</h3>
<div class="box">
<input type="checkbox" value="test1">
<p>test1</p>
</div>
<div class="box">
<input type="checkbox" value="test2">
<p>test2</p>
</div>
<div class="print">
Print
</div>
</section>
<section class="section section-two" id="r2">
<h3>Section 2</h3>
<div class="box">
<input type="checkbox" value="test3">
<p>test3</p>
</div>
<div class="box">
<input type="checkbox" value="test4">
<p>test4</p>
</div>
<div class="print">
Print
</div>
</section>
<section class="section section-three" id="r3">
<h3>Section 3</h3>
<div class="box">
<input type="checkbox" value="test5">
<p>test5</p>
</div>
<div class="box">
<input type="checkbox" value="test6">
<p>test6</p>
</div>
<div class="print">
Print
</div>
</section>
querySelectorAll returns a static NodeList, i.e. the list will reflect the state at invocation and won't update if the page later changes.
The following line runs when you initialize your page:
let terms = document.querySelectorAll(".active input[type='checkbox']");
And that's why you always capture the first section in local storage.
You need to move this line inside your click handler so that you enumerate the checkboxes inside the .active section at that time.
Remove the Attribute ".change" from your selector on line 23
simply change
let terms = document.querySelectorAll(".active input[type='checkbox']");
to
let terms = document.querySelectorAll("input[type='checkbox']");
I have a list like this.
Inside each .list item there is a html button :
<div class="list">
<button>.list</button>
</div>
Also, each item can be inside a .bloc element
<div class="list"><button>.list</button></div>
<div class=bloc>
<div class="list"><button>.list</button></div>
</div>
When I click on the button, I would like the previous .list item to have the .active class like so :
Well it’s pretty easy with jquery and i've done that, it’s work pretty well :
$('.list button').on('click', function() {
$(this).closest('.list').prev('.list').addClass('active');
});
BUT i have some specific cases :
Sometimes the list items can be hidden and a list with hidden class can’t have .active class :
Or more complicated. You have to go up on each item one by one and put the active class to the first which does not have the hidden class :
I did the mechanics for items without class hidden, but I'm afraid I'm going in the wrong direction because the number of cases is getting bigger and bigger. Ain't there a smarter way ? :o
$('.list button').on('click', function() {
if ($(this).closest('.list').prev().length === 0) {
if ($(this).closest('.bloc').length) {
$(this).closest('.bloc').prev('.list').addClass('active');
$(this).closest('.bloc').prev('.bloc').find('.list:last-child').addClass('active');
} else {
$(this).closest('.list').next('.list').addClass('active');
}
}
if ($(this).closest('.list').prev('.bloc').length) {
$(this).closest('.list').prev('.bloc').find('.list:last-child').addClass('active');
}
$(this).closest('.list').prev('.list').addClass('active');
}
Rather than use .closest .prev and .next you can use the overload to .index which will give you the index within an existing collection.
var idx = collection.index(element);
select all your .list items into a jquery object/collection
when clicking get the index within that collection
subtract 1 to get the previous .list item within that collection
The basic scenarios are covered with $(".list") :
// collate the list first
var list = $(".list");
// add click handler
list.click(function() {
// confirm there are no duplicates
// comapred with $(this).index() which is the index within the parent
console.log(list.index(this), $(this).index())
$(".active").removeClass("active");
var idx = list.index(this);
if (idx > 0)
list.eq(idx-1).addClass("active");
});
.list { border:1px solid #CCC; height: 20px; }
.bloc { border:1px solid #444; padding: 5px; }
.active { border:1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrapper'>
<div class='bloc'>
<div class='list'></div>
<div class='list'></div>
</div>
<div class='list'></div>
<div class='list'></div>
</div>
All the other use-cases are then just a case of providing the correct selector up-front, with otherwise exactly the same code
var list = $(".wrapper>.bloc:not(.hidden)>.list:not(.hidden),.wrapper>.list:not(.hidden)");
I've tried to recreate some of your scenarios, but if there's one that's missing, please comment and I'll ensure it fits (within the remit of the question).
Giving:
var list = $(".wrapper>.bloc:not(.hidden)>.list:not(.hidden),.wrapper>.list:not(.hidden)")
list.click(function() {
$(".active").removeClass("active");
var idx = list.index(this);
if (idx > 0)
list.eq(idx-1).addClass("active");
});
.list { border:1px solid #CCC; height: 20px; }
.bloc { border:1px solid #444; padding: 5px; }
.active { border:1px solid red; }
.hidden { background-color: #ccc; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrapper'>
<div class='bloc'>
<div class='list'></div>
<div class='list'></div>
</div>
<div class='list hidden'></div>
<div class='bloc'>
<div class='list hidden'></div>
<div class='list hidden'></div>
</div>
<div class='list'></div>
<div class='bloc'>
<div class='list hidden'></div>
<div class='list'></div>
</div>
<div class='list'></div>
<div class='list'></div>
<div class='bloc hidden'>
<div class='list'></div>
<div class='list'></div>
</div>
<div class='list'></div>
<div class='list'></div>
</div>
I'm making a personal webpage and I'm using JavaScript to create a typing effect under a header called "My Story". The text types fine, but once it is done typing the cursor remains at the bottom. What do I need to change/add in my code to fix this?
I want the cursor to disappear once the text is type. No error messages are present.
// Displays "My Story" with a typing effect
var _CONTENT = ["When I was 15, I took a Robotics Honors course at my high school. We designed and built robots using VEX robotics kits. To me, the most interesting part was building the drag-and-drop code and uploading it to the robot to control it. This is what inspired me to code. Before long, I was researching software development and decided the best language for me to start with would be Python. That was a year ago, and since then I've worked in HTML, CSS, JavaScript, and Java, and plan to further expand my developer capabilities from this point on."];
var _PART = 0;
var _PART_INDEX = 0;
var _INTERVAL_VAL;
var _ELEMENT = document.querySelector("#text");
var _CURSOR = document.querySelector("#cursor");
function Type() {
var text = _CONTENT[_PART].substring(0, _PART_INDEX + 1);
_ELEMENT.innerHTML = text;
_PART_INDEX++;
if (text === _CONTENT[_PART]) {
_CURSOR.style.display = "none";
clearInterval(_INTERVAL_VAL);
setTimeout(function() {
_INTERVAL_VAL = setInterval(Delete, 50);
}, 1000);
}
}
_INTERVAL_VAL = setInterval(Type, 100);
body {
background: dodgerblue !important;
color: white !important;
}
h3 {
border-left: 6px solid whitesmoke;
background-color: lightslategray;
}
p5 {
text-align: justify;
}
p4 {
text-align: justify;
}
#container {
text-align: center;
}
#text {
display: inline-block;
vertical-align: middle;
color: white;
letter-spacing: 2px;
}
#cursor {
display: inline-block;
vertical-align: middle;
width: 3px;
height: 50px;
background-color: white;
animation: blink .75x step-end infinite;
}
#keyframes blink {
from,
to {
background-color: transparent;
}
50% {
background-color: black;
}
}
::-webkit-scrollbar {
width: 5px;
}
::-webkit-scrollbar-track {
background: whitesmoke;
}
::-webkit-scrollbar-thumb {
background: grey;
}
::-webkit-scrollbar-thumb:hover {
background: dodgerblue;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="row align-items-start">
<div class="col">
<nav class="navbar navbar-expand-sm bg-light navbar-light fixed-top">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Me</a>
</li>
</ul>
</nav>
<header>
<title>
Robert Smith
</title>
</header>
<body>
<p class="bg-primary text-white">
</div>
<div class="col ml-auto"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col">
<h1>
<b>
<div class = "p-4 mt-5 align-baseline border bg-light text-dark" style = "width:300px" > Robert Smith </div>
</b>
</h1>
<h2 class="display-4 ml-3"> I want to make a difference.
</h2>
<h3>
<div class="ml-3">
My Story
</div>
</h3>
<divT>
<p1>
<div id="container">
<div id="text"></div>
<div id="cursor"></div>
</div>
<span class="border border-dark">
<div class = "ml-3" >
<br>
</div>
</span>
</p1>
<p6>
<div class="ml-3">
I love to code, whether it's building websites like this <br> or turning my ideas into a reality. <br> I hope I can also do the same for yours.
</div>
</p6>
</divT>
<h4>
Contact me
</h4>
<p6>
<ul3>
<li>Email: robertethansmith#yahoo.com</li>
<li>GitHub: roberto257</li>
</ul3>
</p6>
</div>
<div class="col">
<script language="javascript">
//Changes images when clicked
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith.JPG") {
document.getElementById("imgClickAndChange").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith3.JPG";
} else {
document.getElementById("imgClickAndChange").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith.JPG";
}
}
function changeImage2() {
if (document.getElementById("imgClickAndChange2").src == "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith2.JPG") {
document.getElementById("imgClickAndChange2").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith1.JPG";
} else {
document.getElementById("imgClickAndChange2").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith2.JPG";
}
}
</script>
<p2>
<img src="file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith.JPG" class="img-fluid rounded img-thumbnail" alt="Me" id="imgClickAndChange" onclick="changeImage()" />
<img src="file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith2.JPG" class="img-fluid rounded img-thumbnail" alt="Me" id="imgClickAndChange2" onclick="changeImage2()" />
</p2>
</div>
<div class="col mt-5">
<p5>
<br> I have been coding for over a year now and am comfortable coding and building applications and developing programs on my own.
<br><b>I am not afraid to tackle <ins>any</ins> challenge a client presents me and will only decline if I
truly feel that I cannot complete the proposed task to the sufficient expectations of the client.</b> <br>
</p5>
<img src="file:///Users/roberto257/Desktop/Coding/Portfolio/Website/python.png" alt="Python">
<p4>
<br> My current skills include but are not limited to:
<ul2>
<li>Python</li>
<li>Web Development</li>
<li>JavaScript</li>
<li>Java</li>
</ul2>
I am <i> always </i> working to improve my current skills in languages, frameworks, libraries, and APIs and hope to continue to learn new ones. <br>
</p4>
</div>
</div>
<div class="row">
<div class="col">
</div>
<div class="col"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
Maybe, try this? I'm adding pseudo-class:after, with content: '|' and removing the class at the end.
(function(){
/* cut the text for demo */
let text = "When I was 15, I took a Robotics Honors course at my high school."
let bubu = document.getElementById('bubu');
for( let i = 0; i < text.length; i++ ){
setTimeout( function(){
bubu.innerText += text.charAt(i);
}, i*100);
}
setTimeout(function(){
document.getElementById('bubu').classList.remove('bubu');
}, (text.length)*100); /* Set removing Timeout, synchronous to the end of typing */
})();
#bubu {
text-align: center;
width: 400px;
font-size: 20px;
}
.bubu:after {content: '|'; color: red;}
<div id="bubu" class="bubu"></div>
P.s. I've used text.split('') - to sort each character into array...
Changed → text.charAt(i); due to comment*
Just like you are inserting text from array, insert the cursor as well after the text/innerHtml. Try running the snippet, is that what you are expecting?
Only change made - _ELEMENT.appendChild(_CURSOR);
// Displays "My Story" with a typing effect
var _CONTENT = ["When I was 15, I took a Robotics Honors course at my high school. We designed and built robots using VEX robotics kits. To me, the most interesting part was building the drag-and-drop code and uploading it to the robot to control it. This is what inspired me to code. Before long, I was researching software development and decided the best language for me to start with would be Python. That was a year ago, and since then I've worked in HTML, CSS, JavaScript, and Java, and plan to further expand my developer capabilities from this point on."];
var _PART = 0;
var _PART_INDEX = 0;
var _INTERVAL_VAL;
var _ELEMENT = document.querySelector("#text");
var _CURSOR = document.querySelector("#cursor");
function Type() {
var text = _CONTENT[_PART].substring(0, _PART_INDEX + 1);
_ELEMENT.innerHTML = text;
_ELEMENT.appendChild(_CURSOR);
_PART_INDEX++;
if (text === _CONTENT[_PART]) {
_CURSOR.style.display = "none";
clearInterval(_INTERVAL_VAL);
setTimeout(function() {
_INTERVAL_VAL = setInterval(Delete, 50);
}, 1000);
}
}
_INTERVAL_VAL = setInterval(Type, 100);
body {
background: dodgerblue !important;
color: white !important;
}
h3 {
border-left: 6px solid whitesmoke;
background-color: lightslategray;
}
p5 {
text-align: justify;
}
p4 {
text-align: justify;
}
#container {
text-align: center;
}
#text {
display: inline-block;
vertical-align: middle;
color: white;
letter-spacing: 2px;
}
#cursor {
display: inline-block;
vertical-align: middle;
width: 3px;
height: 50px;
background-color: white;
animation: blink .75x step-end infinite;
}
#keyframes blink {
from,
to {
background-color: transparent;
}
50% {
background-color: black;
}
}
::-webkit-scrollbar {
width: 5px;
}
::-webkit-scrollbar-track {
background: whitesmoke;
}
::-webkit-scrollbar-thumb {
background: grey;
}
::-webkit-scrollbar-thumb:hover {
background: dodgerblue;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="row align-items-start">
<div class="col">
<nav class="navbar navbar-expand-sm bg-light navbar-light fixed-top">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Me</a>
</li>
</ul>
</nav>
<header>
<title>
Robert Smith
</title>
</header>
<body>
<p class="bg-primary text-white">
</div>
<div class="col ml-auto"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col">
<h1>
<b>
<div class = "p-4 mt-5 align-baseline border bg-light text-dark" style = "width:300px" > Robert Smith </div>
</b>
</h1>
<h2 class="display-4 ml-3"> I want to make a difference.
</h2>
<h3>
<div class="ml-3">
My Story
</div>
</h3>
<divT>
<p1>
<div id="container">
<div id="text"> </div>
<div id="cursor"></div>
</div>
<span class="border border-dark">
<div class = "ml-3" >
<br>
</div>
</span>
</p1>
<p6>
<div class="ml-3">
I love to code, whether it's building websites like this <br> or turning my ideas into a reality. <br> I hope I can also do the same for yours.
</div>
</p6>
</divT>
<h4>
Contact me
</h4>
<p6>
<ul3>
<li>Email: robertethansmith#yahoo.com</li>
<li>GitHub: roberto257</li>
</ul3>
</p6>
</div>
<div class="col">
<script language="javascript">
//Changes images when clicked
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith.JPG") {
document.getElementById("imgClickAndChange").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith3.JPG";
} else {
document.getElementById("imgClickAndChange").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith.JPG";
}
}
function changeImage2() {
if (document.getElementById("imgClickAndChange2").src == "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith2.JPG") {
document.getElementById("imgClickAndChange2").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith1.JPG";
} else {
document.getElementById("imgClickAndChange2").src = "file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith2.JPG";
}
}
</script>
<p2>
<img src="file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith.JPG" class="img-fluid rounded img-thumbnail" alt="Me" id="imgClickAndChange" onclick="changeImage()" />
<img src="file:///Users/roberto257/Desktop/Coding/Portfolio/Website/robertsmith2.JPG" class="img-fluid rounded img-thumbnail" alt="Me" id="imgClickAndChange2" onclick="changeImage2()" />
</p2>
</div>
<div class="col mt-5">
<p5>
<br> I have been coding for over a year now and am comfortable coding and building applications and developing programs on my own.
<br><b>I am not afraid to tackle <ins>any</ins> challenge a client presents me and will only decline if I
truly feel that I cannot complete the proposed task to the sufficient expectations of the client.</b> <br>
</p5>
<img src="file:///Users/roberto257/Desktop/Coding/Portfolio/Website/python.png" alt="Python">
<p4>
<br> My current skills include but are not limited to:
<ul2>
<li>Python</li>
<li>Web Development</li>
<li>JavaScript</li>
<li>Java</li>
</ul2>
I am <i> always </i> working to improve my current skills in languages, frameworks, libraries, and APIs and hope to continue to learn new ones. <br>
</p4>
</div>
</div>
<div class="row">
<div class="col">
</div>
<div class="col"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
Unless I'm misunderstanding what you are asking for, it looks like you are just missing a Delete function to get triggered, once the typing is done. Something like this should do the trick:
function Delete() {
_CURSOR.style.display = "none";
}
I like OPTIMUS PRIME idea(+1), but it also should better works with setInterval
I have some remarks:
1 - using textContent is more apopriate (if you don't use html tags)
2 - using arrow function to impact local vars
3 - you don't need CSS to set a Blinking Cursor
So I made this (It use html tags)
It works also if JS is disabled (no animation, but the text is shown)
Text_Typed('bubu');
function Text_Typed( eID, delay = 100)
{
let
element = document.getElementById(eID),
txt = element.innerHTML,
Text_Sz = txt.length,
sItv_id = null,
Text_html = '',
loop_i = -1,
Cursor_i = 1;
element.textContent = '▮'; // or '|';
sItv_id = setInterval(_=>{
loop_i++;
if (loop_i < Text_Sz)
{
let n, inC = txt.charAt(loop_i);
switch (inC) {
case '<':
n = txt.indexOf('>',loop_i);
if (n>0)
{
inC = txt.substring(loop_i,++n);
loop_i = --n;
}
break;
case '&':
n = txt.indexOf(';',loop_i);
if (n>0)
{
inC = txt.substring(loop_i,++n);
loop_i = --n;
}
break;
}
Cursor_i = (Cursor_i+1) % 2;
Text_html += inC;
element.innerHTML = Text_html + ((Cursor_i)?'▮':'▯'); // or '|' ▉
}
else {
element.innerHTML = Text_html;
clearInterval(sItv_id);
}
}, delay);
}
#bubu {
text-align : center;
width : 400px;
font-size : 20px;
}
<div id="bubu" >
<p>When I was 15, I took a Robotics Honors course at my high school.</p>
<p>We designed and built robots using <span style="color:crimson">VEX robotics kits</span>.</p>
<p>To me, the most interesting part was building the drag-and-drop code and uploading it to the robot to control it.</p>
<p>This is what inspired me to code.</p>
<p>Before long, I was researching software development and decided the best language for me to start with would be Python.</p>
<p>That was a year ago, and since then I've worked in HTML, CSS, JavaScript, and Java, and plan to further expand my developer
<b>capabilities</b> from this point on.</p>
</div>
This question already has answers here:
How to change div background color on button click?
(2 answers)
Closed 3 years ago.
I'm very new to coding and have learned my very limited knowledge from forums and tutorials online. I seem to be up against a problem that I cannot for the life of me figure out.
My goal is to press one of three buttons (Leadership, Program, Team) at the top of a grid (the grid lists our services) and have the appropriate grid box change colors. For example, pressing the Leadership button would turn a grid box blue, Program would turn a grid box yellow, and Team would turn a grid box green. This means that a grid box might be linked to more than one of the buttons, as our services overlap. So depending on what button is pressed, a single grid box might change to blue, yellow, or green.
I figured out how to do toggle buttons which show the body onclick. BUT that means A LOT of redundancy. (I would have to do a grid with the appropriately colored boxes for Leadership, another one for Program, and another one for Team). So, I think I'm on the wrong path there.
I've searched toggles, buttons, anchors, event listeners, targets, you name it. It seems like it all relates to the button itself, not how the button relates to an element on the page.
I am very grateful to anyone who can point me in the right direction! Thank you!
function goToAnchor(anchor) {
var loc = document.location.toString().split('#')[0];
document.location = loc + '#' + anchor;
return false;
}
var divs = ["Div1", "Div2", "Div3", "Div4"];
var visibleDivId = null;
function divVisibility(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";
}
}
}
.square-grey {
display: table-cell;
height: 100px;
width: 600px;
text-align: center;
vertical-align: middle;
border-radius: 5%;
/*make it pretty*/
background: #F5F5F5;
color: #999999;
padding: 10px 15px 10px 15px;
font: 20px "helvetica";
font-weight: 350;
box-shadow: 2px 3px 3px #999999;
}
div.highlit {
padding: 25px;
}
<div class="row">
<div class="buttons">
<div style="text-align:center">
<div class="col-sm-4">
Enterprise
</div>
<div class="col-sm-4">
Program
</div>
<div class="col-sm-4">
Team
</div>
</div>
</div>
</div>
<div class="inner_div">
<div id="Div1">
<div class="row">
<div style="text-align:center">
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Strategic Alignment
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Adaptive Leadership
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Portfolio Management
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Cultural Shift
</div>
</div>
</div>
</div>
</div>
</div>
<div id="Div2" style="display: none;">I'm Div Two</div>
<div id="Div3" style="display: none;">I'm Div Three</div>
</div>
</div>
Edited answer, you can add IDs to the boxes and pass them to function.
const changeColor = (elements, color) => {
elements.forEach(el => {
const element = document.querySelector(el);
element.style.backgroundColor = color;
})
}
.colorbox {
width: 100px;
height: 100px;
background-color: aquamarine;
margin-bottom: 10px;
}
<div class="colorbox" id="colorbox1"></div>
<div class="colorbox" id="colorbox2"></div>
<div class="colorbox" id="colorbox3"></div>
<button onclick="changeColor(['#colorbox1', '#colorbox3'], 'tomato')">Change 1 & 3 to tomato</button>
<button onclick="changeColor(['#colorbox1', '#colorbox2'], 'aliceblue')">Change 1 & 2 to aliceblue</button>
<button onclick="changeColor(['#colorbox2', '#colorbox3'], '#ff0000')">Change 2 & 3 to reddest</button>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new to Javascript and only have very basic knowledge of it at this stage.
I am trying to create a filter bar that, when clicked, would set the opacity of the non-matched items to 0.2 and the matched item would remain at full opacity.
I have uploaded the html/css to show an example on jsfiddle: https://jsfiddle.net/rebeccasmith1301/zw2aozff/
<div id="filter-bar">
<button onclick="findShoes()">Shoes</button>
<button onclick="findTops()">Tops</button>
<button onclick="findSkirts()">Skirts</button>
</div>
<div class="product-item">
<p>Shoes</p>
</div>
<div class="product-item">
<p>Tops</p>
</div>
Skirts
I have been experimenting with javascript written on a previous post that I found very helpful but due to my basic knowledge I have been unable to solve how to achieve the results I am aiming for.
I basically would like the user to be able to click on the button shoes (for example) and all of the divs that contain the word shoes to remain with full opacity and all other divs to have the class un-selected which lowers the opacity to 0.2. The divs that contain the products can be a class only, not an id as well.
Would anyone be able to help? This would be using mainly vanilla javascript.
Many thanks,
Becky
Fiddle with multiple words: https://jsfiddle.net/qucwvqfr/1/
Fiddle with white space removal: https://jsfiddle.net/d15v3x0w/1/
Don't make a function for each possible variation of content, just make one function and give that a parameter. This javascript would check the textContent of the items, strip the whitespace from them, and change classes accordingly. The hasClass, addClass, and removeClass are helpers, focus on the highlightItems function.
function hasClass(ele,cls) {
return !!ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
var highlightItems = function(itemName) {
var p = document.getElementsByClassName("product-item");
for (var i = 0; i < p.length; i++) {
itemText = p[i].textContent.replace(/^\s+|\s+$/g,''); // you don't need the .replace() part if you don't add extra white space in the HTML
if ( !(itemText == itemName) ) {
addClass(p[i], "un-selected");
} else {
removeClass(p[i], "un-selected");
}
}
}
And you would use it like this:
<div id="filter-bar">
<button onclick="highlightItems('Shoes')">Shoes</button>
<button onclick="highlightItems('Tops')">Tops</button>
<button onclick="highlightItems('Skirts')">Skirts</button>
</div>
Note:
If you want to have multiple words inside the box, don't add any unnecessary white space inside the div tags. (You probably shouldn't do it anyway.) So the HTML usage would be like this:
<div class="product-item">Shoes and socks</div>
<div class="product-item">Tops</div>
<div class="product-item">Skirts</div>
Credits for the class-changing functions go to http://jaketrent.com/post/addremove-classes-raw-javascript/
There needs to be a reliable way to select the specified items. I propose that you add a class shoes, tops and skirts to their respective elements:
<div class="product-item shoes">
Shoes
</div>
<div class="product-item tops">
Tops
</div>
<div class="product-item skirts">
Skirts
</div>
Now, to select all elements that got shoes it's really easy:
var shoes = document.getElementsByClassName('shoes');
Selecting elements that don't have a class shoes is another story. Let say we start by collecting out all product-item elements, like so:
var products = document.getElementsByClassName('product-item');
From here on, you need to iterate all the elements inside the returned nodeList and check if they got a shoes class. A helper function that can help you with that:
function not(nodeList, cls){
var reg = new RegExp('\\b' + cls + '\\b');
return Array.prototype.reduce.call(nodeList, function(acc, el){
console.log(el, el.className.search(reg))
if(el.className.match(reg) === null){
acc.push(el);
}
return acc;
}, []);
}
So now, to get products that aren't shoes:
var notShoes = not(products, 'shoes');
To change the opacity of all the elements inside a nodeList we could use another helper function:
function changeOpacity(nodeList, opacity){
Array.prototype.forEach.call(nodeList, function(el){
el.style.opacity = opacity;
});
}
And to use it:
changeOpacity(shoes, 1.0);
changeOpacity(notShoes, 0.2);
All together in this snippet:
function find(cls) {
var clsList = document.getElementsByClassName(cls);
var products = document.getElementsByClassName('product-item');
var notCls = not(products, cls);
changeOpacity(clsList, 1.0);
changeOpacity(notCls, 0.2);
}
function not(nodeList, cls){
var reg = new RegExp('\\b' + cls + '\\b');
return Array.prototype.reduce.call(nodeList, function(acc, el){
console.log(el, el.className.search(reg))
if(el.className.match(reg) === null){
acc.push(el);
}
return acc;
}, []);
}
function changeOpacity(nodeList, opacity){
Array.prototype.forEach.call(nodeList, function(el){
el.style.opacity = opacity;
});
}
/* Styling for filter bar*/
#filter-bar{
width: 100%
}
#filter-bar button{
width: 30%
float: left;
margin: 0.5%;
}
/* Styling for products*/
.product-item{
width: 24%;
float: left;
margin: 0.5%;
background-color: red;
height: 80px;
box-sizing: border-box;
padding: 10px;
}
/* Different options for products with button click*/
.un-selected{
opacity: 0.2;
}
<div id="filter-bar">
<button onclick="find('shoes')">Shoes</button>
<button onclick="find('tops')">Tops</button>
<button onclick="find('skirts')">Skirts</button>
</div>
<div class="product-item shoes">
Shoes
</div>
<div class="product-item tops">
Tops
</div>
<div class="product-item skirts">
Skirts
</div>
<div class="product-item skirts">
Skirts
</div>
<div class="product-item shoes">
Shoes
</div>
<div class="product-item tops">
Tops
</div>
<div class="product-item skirts">
Skirts
</div>
<div class="product-item skirts">
Skirts
</div>
I have a solution with jquery:
HTML
<button class="active btn" id="all">Show All</button>
<button class="btn" id="a">Tops</button>
<button class="btn" id="b">Skirts</button>
<button class="btn" id="c">Shoes</button>
<!-- An element with an id is needed for the jQuery -->
<div id="parent">
<!-- The base class is the box. Categories are then given as accessory classes. Any div can be in more than one category -->
<div class="box product-item a b">Shoes & Tops</div>
<div class="box product-item a">Tops</div>
<div class="box product-item b">Skirts</div>
<div class="box product-item c">Shoes</div>
</div>
CSS
/* Styling for filter bar*/
#filter-bar{
width: 100%
}
#filter-bar button{
width: 30%
float: left;
margin: 0.5%;
}
/* Styling for products*/
.product-item{
width: 24%;
float: left;
margin: 0.5%;
background-color: red;
height: 80px;
box-sizing: border-box;
padding: 10px;
}
/* Different options for products with button click*/
.un-selected{
opacity: 0.2;
}
jQuery
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');
})
jsfiddle
function filter(me) {
var items = document.getElementsByClassName("product-item");
console.log(me.textContent);
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.style.display = "";
if (item.textContent.trim() !== me.textContent.trim() && me.textContent.trim() !== "All") {
item.style.display = "none";
}
}
}
/* Styling for filter bar*/
#filter-bar{
width: 100%
}
#filter-bar button{
width: 30%
float: left;
margin: 0.5%;
}
/* Styling for products*/
.product-item{
width: 24%;
float: left;
margin: 0.5%;
background-color: red;
height: 80px;
box-sizing: border-box;
padding: 10px;
}
/* Different options for products with button click*/
.un-selected{
opacity: 0.2;
}
<div id="filter-bar">
<button onclick="filter(this)">Shoes</button>
<button onclick="filter(this)">Tops</button>
<button onclick="filter(this)">Skirts</button>
<button onclick="filter(this)">All</button>
</div>
<div class="product-item">
Shoes
</div>
<div class="product-item">
Tops
</div>
<div class="product-item">
Skirts
</div>
<div class="product-item">
Skirts
</div>
<div class="product-item">
Shoes
</div>
<div class="product-item">
Tops
</div>
<div class="product-item">
Skirts
</div>
<div class="product-item">
Skirts
</div>