Querying html for an id in JS - javascript

I am in the process of completing CS50 and a took the WEB Tracks. I am currently searching for a solution with a JS problem.
function blink() {
let body = document.querySelector('body');
if (body.style.visibility === 'hidden') {
body.style.visibility = 'visible';
} else {
body.style.visibility = 'hidden';
}
}
// Blink every 500ms
window.setInterval(blink, 500);
This is a working solution, however I need to alter it so that it selects all specific ids. For example id="image". I found an adaptation that only select 1 picture and makes it blink. How do i make all three blink?
There is an obvious solution with writing more code, but i hope there is another way

you will try with:
document.querySelector('#image') // return first item
document.querySelectorAll('#image') // return array items
document.getElementById('image') // similar to querySelector('#image')
maybe you can try with selector [id='image'] if for some reason #id not working properly.
example:
setTimeout(() => {
document.querySelector('#image').style.visibility = 'visible'
}, 2000);
let interval;
interval = setInterval(() => {
const image = document.querySelector('#image');
if (image && image.style.visibility !== 'hidden') {
clearInterval(interval);
alert("is visible");
}
}, 500);
<img style="visibility: hidden;" src="https://www.gravatar.com/avatar/dab6fe88b302678ad222467965a0423e?s=48&d=identicon&r=PG" id="image" />
css selectors(examples):
#someId - search by id
a - find a tag
[attribute='value'] - find by attribute value
.className - find by class
:not(.className) - find where not

Related

How can I simplify my js code for css animation?

I made CSS animations and buttons to play the animations and use add and remove classes to play each motion. I didn't use a toggle because if I use a toggle, it mixes with other buttons.
I've seen many CSS animations that didn't use js at all.
Is there any way to reduce my js code and simplify it?
Here is the code-
playbtn.addEventListener("click", function (e) {
e.preventDefault;
ball.style.display = "block";
bowl.style.display = "none";
ball.classList.remove("ball-move");
ball.offsetWidth = ball.offsetWidth;
ball.classList.add("ball-move");
document.getElementById('dFace').className = '';
dFace.offsetWidth = dFace.offsetWidth;
dFace.classList.add("p-head-move");
document.getElementById('ear').className = '';
ear.offsetWidth = ear.offsetWidth;
ear.classList.add("lean");
document.getElementById("mouthid").className = '';
mouth.offsetWidth = mouth.offsetWidth;
mouth.classList.add("mouth-move");
}, false);
I think you have to read about Animation play state api, that will reduce your code.
Doc Link!
1, From your code, I assume that bowl, ball, dFace, ear and mouth are all HTMElement that have already assigned with a value from document.getElementById. So, you may not have to get the HTMLElement again in this functions.
2, You may not need to assign the value for offsetWidth as it is a read-only property as described in https://www.w3schools.com/jsref/prop_element_offsetwidth.asp. You can remove those lines.
You might be missing () for e.preventDefault
I will suggest the followings:
playbtn.addEventListener("click", function (e) {
e.preventDefault();
ball.style.display = "block";
bowl.style.display = "none";
ball.classList.remove("ball-move");
ball.classList.add("ball-move");
dFace.className = '';
dFace.classList.add("p-head-move");
ear.className = '';
ear.classList.add("lean");
mouth.className = '';
mouth.classList.add("mouth-move");
}, false);
Also, the action on dFace, ear and mouth are similar, so you may wrap it in a function call restartAnimation to further reduce duplications of your code.
const restartAnimation = (ele, className) => {
ele.className = '';
ele.classList.add(className);
}
playbtn.addEventListener("click", function (e) {
e.preventDefault();
ball.style.display = "block";
bowl.style.display = "none";
ball.classList.remove("ball-move");
ball.classList.add("ball-move");
restartAnimation(dFace, "p-head-move")
restartAnimation(ear, "lean")
restartAnimation(mouth, "mouth-move")
}, false);
You should include your CSS in your post as well! But I think you could avoid the restartAnimation instances you have by using animation-iteration-count: infinite; (if you are trying to make your animations loop, for example) in the CSS selector for the animated parts. I would recommend looking into the CSS animation documentation here as it's very clear! Good luck!

How Can I Install a Filter to a Carousel - Javascript

Hi guys I have an issue that I have been trying to sort out but cannot think of the way to solve the issue so wondering if someone can enlighten me a little,
I have built a carousel using Kevin Powells Video online
It will function as a way to display blog posts for a website with each one being a link to the blog post it is referencing
The issue I am encountering relates to me trying to implement a filter on the carousel so that when something is searched the carousel displays only the posts that match what is typed (or close to)
The search is operational but the targeted slides don't prepend to the start of the track and instead stay in the same place,
Here is the fiddle so you can see: https://jsfiddle.net/DanielHeery/1fjhq8m0/7/
Thank you!!
// JavaScript
let slideWidth = slides[0].getBoundingClientRect().width;
// Set Slide Position
const setSlidePositon = (slides, index) => {
slides.style.left = slideWidth * index + 'px'
};
// Filter
filter.addEventListener('keyup', e => {
prevBtn.classList.add('is-hidden')
nextBtn.classList.add('is-hidden')
const text = e.target.value.toLowerCase()
const slideContent = document.querySelectorAll('.slide__heading')
let items = new Array();
slideContent.forEach(function(slideTxt){
if(slideTxt.innerText.toLowerCase().indexOf(text) != -1) {
items.push(slideTxt.parentElement.parentElement.parentElement)
slideTxt.parentElement.parentElement.parentElement.style.display = 'block';
}
else {
slideTxt.parentElement.parentElement.parentElement.style.display = 'none';
}
})
items.forEach(function(item){
slides.unshift(item)
})
if(text == '') {
prevBtn.classList.add('is-hidden')
nextBtn.classList.remove('is-hidden')
slides.forEach(function(slide){
if (slide === slide [0] && slide.classList.contains('current-slide') === false){
return
} else if (slide.classList.contains('current-slide')){
slide.classList.remove('current-slide')
} else {
slides[0].classList.add('current-slide');
}
})
}
});

How to make div disappear after clicking the button? [duplicate]

This question already has answers here:
Show/Hide Requires a Double-click
(2 answers)
Closed 2 years ago.
Like in the topic. After clicking empty gear (norm) I want to make it change to filled (hov) and show up div (show), but it doesn't work.
Before using ifs everything was working, so there must be something wrong with them.
js:
function list() {
if (document.getElementById('hov').style.display === 'none') {
document.getElementById('norm').style.display = 'none';
document.getElementById('hov').style.display = 'flex';
document.getElementById('show').style.display = 'grid';
}
if (document.getElementById('hov').style.display === 'flex') {
document.getElementById('norm').style.display = 'flex';
document.getElementById('hov').style.display = 'none';
document.getElementById('show').style.display = 'none';
}
}
html:
<button class="men" onclick="list()"><img id="norm" src="img/gearw.png" height="28px"><img id="hov" src="img/gearwhover.png" height="28px"></button>
Did you write link to JQuery?
write <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> into the end of the body, but before body. If it doesn't work, sorry( I can't give another advice
I think you have a bit of a misunderstanding of what display does (you can read up on it here: https://www.w3schools.com/cssref/pr_class_display.asp). Setting it to none won't make it invisible. Instead, you could use visibility.
For example:
function list() {
var norm = document.getElementById("norm");
var hov = document.getElementById("hov");
if (hov.style.visibility === "hidden") {
norm.style.visibility = "hidden";
hov .style.visibility = "visible";
} else if (hov.style.visibility === "visible") {
norm.style.visibility = "visible";
hov .style.visibility = "hidden";
}
}
<button class = "men" onclick = "list()">
<img id = "norm" src = "img/gearw.png" height = "28px">
<img id = "hov" src = "img/gearwhover.png" height = "28px" style = "visibility: hidden">
</button>
Other than that, your code seems very weird (your JS talks about a "show" element that's not in your HTML document?), and its not quite clear from the question what you're trying to accomplish. There probably is a much more elegant way to do what you want, but without telling us, we can't know.
If I were to guess, I'd say that you were trying to make the image on the button change when the user hovers over it, in which case you'd probably be better off using CSS for that, but again I can't know for sure.
Anyways, I wish you the best of luck in your project!

javascript/htmlDOM display element while hiding the others

So I have written this clickDisplay function that displays certain elements on click, it works fine, yes, but obviously I needed a feature that would hide all the other elements, because they are supposed to be displayed in the same field, so right now they kind stack on top of eachother
this is what I came up with, but it sorta doesn't work and I don't know why
const pages = ['watch','chars','seasons','songs']
function clickHide(element){
document.getElementById(element).style.display = 'none';
}
function clickDisplay(element){
document.getElementById(element).style.display = 'block';
for(let x = 0 ; x < pages.length ; x++){
if (pages[x]!=element){clickHide(pages[x]);}
}
}
While it sounds like you solved your own problem, I started putting together code before you posted, so I'll throw it up here for you. :)
const pages = ['watch', 'chars', 'seasons', 'songs']
function clickHide (el) {
pages.forEach((pel) => {
setElement(pel, pel === el ? 'none' : 'block')
})
}
function setElement(el, attr) {
document.getElementById(el).style.display = attr
}
with the html having this:
onclick="clickHide('watch')" // or 'chars' 'seasons' or 'songs'
Oh wait, I don't know why but this suddenly works now. I only changed the placeholder text and refreshed the page
But I'm sure that this still is a stupid solution

How to remove or reset CSS style using JS?

I want either remove or reset a style applied on a particular DOM node using JS.
node.style.webkitTransitionDuration = '5000ms';
node.style.webkitTransformOrigin = '200px 200px';
node.style.webkitTransform = 'rotateZ(25rad)';
I want to reset/set webkitTransform time and again on a fire of an event
Tried like this
node.style.webkitTransform = 'rotateZ(0rad)';
node.style.webkitTransform = 'rotateZ(25rad)';
But its not working.
P.S. Can not use any framework.
Here's an example that should fit your needs. It toggles when you click on the document. Note: it of course only works in Webkit-based browsers.
animateNode(document.getElementById("test"), "5000ms", "200px 200px", "rotateZ(25rad)");
var toggle = toggleValue();
function animateNode(node, duration, origin, transform)
{
node.style['webkitTransitionDuration'] = duration;
node.style['webkitTransformOrigin'] = origin;
node.style['webkitTransform'] = transform;
}
function toggleValue() {
var num = 1;
return function ()
{
return ++num;
};
}
document.onclick = function()
{
var toggleNum = toggle();
if(toggleNum % 2 === 0)
{
animateNode(document.getElementById("test"), "5000ms", "200px 200px", "rotateZ(0rad)");
}else if(toggleNum % 2 === 1)
{
animateNode(document.getElementById("test"), "5000ms", "200px 200px", "rotateZ(25rad)");
}
}
http://jsfiddle.net/GdGw7/3/
If you are looking to remove the rule from the element then this should work:
node.style.webkitTransform = '';
You say you don't want to use a framework. but if it is OK (according to your comment) to do so:
You can use jQuery:
so you can do in jQuery:
$('selector').css({
webkitTransitionDuration = '5000ms',
webkitTransformOrigin = '200px 200px',
webkitTransform = 'rotateZ(25rad)'
})
you can clear out the style element with:
$('selector').attr('style','');
add class:
$('selector').addClass('newClass');
remove class:
$('selector').removeClass('rClass');

Categories

Resources