I got a problem with my javascript code . I want to have a function that if I click the class or a id , it will add css class so the ui will different if the button is clicked , and I want to make it look like normal when the button click again . This is my code
function Menu(e) {
let list = document.querySelector('ul');
e.name === 'menu' ? (e.name = "close", list.classList.add('top-[80px]'), list.classList.add('opacity-100')) :
(e.name = "menu", list.classList.remove('top-[80px]'), list.classList.remove('opacity-100'))
if (e) {
$('.navbar').addClass("sticky-costum-2");
} else {
$('.navbar').removeClass("sticky-costum-2");
}
};
the context is I want to make my navbar look bigger when user click the burger button , so it will add class
"sticky-costum-2" to make it bigger .
but the problem is , if I click again to close the burger button , it not remove the class , I know that I'm wrong but I'm newbie. I recently have same kind of problem in my last project and this is my code
var b = document.getElementById("button");
var audio = document.getElementById("player");
b.addEventListener("click", function(){
if(audio.paused){
audio.play();
audio.loop='true';
b.innerHTML = "<img class='sticky' src ='https://cdn-icons-png.flaticon.com/512/0/375.png'>";
} else {
audio.pause();
b.innerHTML = "<img class='sticky' src ='https://cdn.icon-icons.com/icons2/933/PNG/512/rounded-pause-button_icon-icons.com_72587.png' >";
}
});
Yea it's an audio player and it works , it can play and pause the audio in the same button , but I have no idea how I can implement this my code to fix my problem .
I don't know if this will solve your problem but it has what has helped me. Instead of styling in the javascript do the styling in the css. What I am saying is when you add the class in the css select that class even though it doesn't exist right now it will exist when you click it. When you remove the class go to the css and check for the normal element or class you had originally. This might solve your problem.
Related
In the code I am working on, the video is not reappearing after it is removed, why is this, and is there a way for that to be fixed or adjusted in the code so that the videos will appear after going back to a previous page?
To reproduce, click on a button to enter a container, then the blue play button, then the exit button, then enter the same button again, the video has not reappeared.
code https://jsfiddle.net/wzaknd08/
function removePlayerHandler(evt) {
const el = evt.target;
let container = el.closest(".container");
let wrappers;
if (container) { //if multiple players
wrappers = container.querySelectorAll(".remove .wrap");
} else { //if single player
container = el.closest(".remove");
wrappers = container.querySelectorAll(".wrap");
}
wrappers.forEach(function (wrapper) {
if (wrapper.player) {
removePlayer(wrapper);
}
});
}
In the demo code here click on the same play button multiple times.
You will see the video stays reappearing.
https://jsfiddle.net/g1ztucmp/
How would that be fixed in the code I am working on so that the videos appear again after going back to view the same videos after they are removed.
Like how it works in the demo code I provided.
You are adding a class to wrap called active when you press the play button.
function showCover(playButton) {
const cover = playButton.parentElement;
cover.classList.add("active");
}
However, you never remove that class when closing the player(s). So when closing the player you need to remove the active class again. This is best done in the removePlayer function as you already iterate though al the classes that might have them.
function removePlayer(wrapper) {
wrapper.player.destroy();
wrapper.classList.remove("active");
delete wrapper.player;
console.log("removePlayer");
}
Change you Fiddle to make it work: https://jsfiddle.net/wqchdey1/. Only change was me adding wrapper.classList.remove("active"); to the removePlayer function
I am trying to loop through a gallery of gradient swathes, to highlight them so they can be edited back in the main image, but hitting a roadblock when clicking them to test they are working. They are in a bootstrap row, as col-md-3's, and each swatch bg has an id of bg-gradient (row id is gallery). The below code works in as much as they become active via the css when hovered, but wont console log a test message on click.
html structure is a bootstrap row with id of "gallery", then 4 col-md-3's with id of "swatch", then the actual bg-gradient is what is being looped through. These become active on hover via css settings not via the JavaScript, but wont console log test message on click.
Demo
Code:
editSwatch() {
let swatchs = document.querySelectorAll('swatch'),
//let swatchs = document.getElementById('gallery'),
links = swatchs.getElementsByTagName('bg-gradient'),
i;
for (i = 0; i < links.length; i += 1) {
links[i].addEventListener('click', function () { console.log('click works') });
}
Updated code as per comments below, but still exactly the same result, tried tagName on the links var and still same.
Seems to be finding the swatches, but not working on click.
Need to get that click working to carry on?
Any tips welcome.
Thanks.
You can not keep same id for swatchs, also you can use below query selector with appropriate selector as parameter and loop through swatchs
var swatchs= document.querySelectorAll(".swatchs");
Technically onclick needs to be a function instead. Currently you are passing the return value of console.log() which is undefined I believe. A function needs to be attached to click event in order to make it work.
You can use addEventListener as the following:
links[i].addEventListener('click', function () { console.log('click works') });
Please see a working example how to attach a click event to a <div>:
const div = document.getElementById('elem');
div.addEventListener('click', function () { console.log('hey hello'); });
<div id="elem">Click me!</div>
I hope this helps!
I have a page with a few filters for search results. These filters are links and upon clicking, I am adding the id to localstorage. When the page reloads it looks in the localstorage if the id of the link exists, it modifies the css of that particular link. I am able to achieve this.
Now, when the same link is clicked again, I need to be able to remove the id of the link from localstoarage so it does not change the css when the page reloads.
Before Clicking
After clicking
Here is my code. Some kind people from StackOverflow helped me get this piece of code together. I need it to extend. Please let me know if any of this doesn't make sense. Would gladly rewrite my sentences.
$(document).ready(function() {
//localStorage.clear();
var cached = localStorage.getItem('filters');
var filters = (cached) ? JSON.parse(cached) : {};
for (id in filters) {
$('#' + id).addClass('li-checked');
}
$('.li-filter').click(function(e) {
//event.preventDefault();
$(e.target).addClass('li-checked');
$(e.target).removeClass('li-unchecked');
var id = $(e.target).attr('id').toString();
if (filters[id]) {
filters[id] += 1;
//filters = $.grep(filters, function(e) { return e.id!=id });
} else {
filters[id] = 1;
}
console.log(JSON.stringify(filters));
localStorage.setItem('filters', JSON.stringify(filters));
});
});
#Rohit If I understood your question correctly, onclick you have to add a class and remove it in case it is already clicked.
For this scenario, I will suggest writing functionality to toggle classes that can help.
You need to get class on the element while li is clicked.
if($(e.target).attr("class").contains("li-checked"))
{
$(e.target).removeClass('li-checked');
$(e.target).addClass('li-unchecked');
}
else if((e.target).attr("class").contains("li-unchecked"))
{
$(e.target).removeClass('li-unchecked');
$(e.target).addClass('li-checked');
}
If the class is 'li-checked' then remove it and add 'li-unchecked'
and if the class is 'li-unchecked' then remove it and add 'li-checked'
I hope it helps.
I have several buttons including divs which they have the same name. unfortunately I can not change the names, they are generated by cms.
So for example when I click only on first button, only the first div is hidden or displayed, and that's fine.
But after refresh page it opens or closes all divs depending is the first div closed or opened, and that I do not want it.
here is the code:
<button class="a">Button</button>
<div class="target"></div>
<button class="a">Button</button>
<div class="target"></div>
$('.a').click(function() {
$(this).next(".target").slideToggle(function() {
localStorage.setItem('visible', $(this).is(":visible"));
});
});
$('.target').toggle(localStorage.getItem('visible') === 'true');
here you can see jsfiddle example: https://jsfiddle.net/pj3gs0z9/3/
So my question is, is it possible to store only clicked button information, and after page refresh display or hide div from only clicked button ?
Thank you
It is possible, but probably not in your case. If you tell us you can't change your button properties, and they are exactly the same, then you won't be able to store different data in your localStorage.
Isn't there any way where you can add some additional information to your button ? It could be a class, an id, a name, or even a data-XXX attribute.
By the way, how are your buttons generated ? are they hard coded, or fetched from a database, or ... ?
EDIT
Here is a way of adding different classes to all of your buttons (althoguh I recommend adding data attributes, but whatever floats your boat) :
let buttons = document.getElementsByTagName('button'); // Array of your buttons
let index = 0;
for (let button of buttons) {
button.className += 'myCustomClass-' + ++index; // Add a custom class to your buttons
}
// Now in your local storage, you can store the class of the button !
EDIT 2 I would store it like this :
// On click, in VanillaJS (sorry, haven't used JQuery in a while)
button.onclick = () => {
let visibleButtons = localStorage.getItem('visible-buttons') || [];
visibleButtons.push(button.className.match(/(myCustomClass-[0-9]*)/)[0]);
}
This is one quick solution, but because of a slideToggle you gonna have a small flash of milliseconds of a visible div unless you first have them hidden and then based on localStorage display them.
$('.a').click(function() {
$(this).next(".target").slideToggle(function() {
localStorage.setItem('visible-' + $(this).index(), $(this).is(":visible"));
});
});
$.each($('.target'), function(k, trg) {
$(trg).toggle(localStorage.getItem('visible-' + $(trg).index()) === 'true');
});
I'm working on this project and I need to add this functionality where we have three products listed.
they started out as div's but changed them to ahref class's to link the entire area.
The box has to change color when hovered - which I have done.
The box needs to change to another color when clicked on - which I have also done.
The one thing I can't figure out is how to make the 2nd box default as selected but then have the color turn off when another one is selected
This is the javascript I have for the page.
var highlightLink = function () {
var active = null, colour = '#f6efa2';
if (this.attachEvent) this.attachEvent('onunload', function () {
active = null;
});
return function (element) {
if ((active != element) && element.style) {
if (active) active.style.backgroundColor = '';
element.style.backgroundColor = colour;
active = element;
}
};
}();
here is one of the boxs
<a class="productBox1" href="#" border="0" onclick="highlightLink(this);">
I'm thinking I need an onload function in the body tag but I don't know what code is needed and I also need it to become unselected when another box is selected.
Any help would be greatly appreciated.
If every link has it's own class anyway, use it as ID instead:
<a id="productBox1" href="#" border="0" onclick="highlightLink(this);">
Use classes for common properties. For identifying single elements, use IDs.
Then you can add this to the bottom of your page (above the closing <body> tag):
<script type="text/javascript">
highlightLink(document.getElementById('productBox1'));
</script>
or set
window.onload = function() {
highlightLink(document.getElementById('productBox1'));
}
in the <head>.
Sounds like you're making this more complicated than it really is. Try this (I'm assuming all your a tags have class productBox1):
$('.productBox1').click(function() {
$('.highlighted').removeClass('highlighted');
$(this).addClass('highlighted');
});
Then have a css class called highlighted which has background-color: #f6efa2.
You need jQuery in order to make this work properly.