I am making a quiz similar to buzzfeed quizzes like THIS. I have the logic planned out and I can kind of see how I'm supposed to code it to act similarly to the one in the link, but I have a problem with the button states.
Here is a fiddle of my code: sample quiz
$(document).ready(function () {
$('#btn1, #a1').click(function () {
$('#a1').removeClass("fadeout");
$('#a1').addClass("highlight");
$('#a2').removeClass("highlight");
$('#a3').removeClass("highlight");
$('#a4').removeClass("highlight");
$('#a5').removeClass("highlight");
$('#a6').removeClass("highlight");
$('#a2').addClass("fadeout");
$('#a3').addClass("fadeout");
$('#a4').addClass("fadeout");
$('#a5').addClass("fadeout");
$('#a6').addClass("fadeout");
btn1.checked = "true";
btn2.checked = "";
btn3.checked = "";
btn4.checked = "";
btn5.checked = "";
btn6.checked = "";
window.alert(document.write(getElementById("btn1").value));
Coding a single question does not seem to be a problem with the ff: change color on hover, reduce opacity of other choices, change to color blue once selected, etc... but as I add more questions, I realized I would have to use addClass and removeClass for the button's effects for every choice for every question, which, as you can see, wouldn't be so practical to code.
Are there any other more efficient ways to do this?
Using the click event of the question div you can apply the classes by using the $this keyword.
$(document).ready(function () {
$('.a_choice').click(function () {
$(this).siblings().removeClass("highlight");
$(this).siblings().addClass("fadeout");
$(this).children('input').prop('checked', true);
$(this).addClass('highlight');
$(this).removeClass("fadeout");
});
});
See http://learn.jquery.com/javascript-101/this-keyword/
Add a class to each button and get them by class instead of by id
$('.quizbuttons').removeClass("fadeout");
The buttons should have the class "quizbuttons" like:
<button class="quizbuttons"></button>
Or whatever element you are using.
Best.
Related
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 have a function that add a class (a animation) on the element, but it is not working as planned.
I want that the user add one class at a time. How verify this? I really don't know how to do that with raw Javascript. With jQuery would be easy, I think, because jQuery has the brilliant one() function.
I try to remove the class when the animation stops, but the user still can add multiple classes. And so, there will be several classes during the animation and will be removed only when the animations are gone. Look:
el.classList.add("test", anotherClass);
el.addEventListener("webkitAnimationEnd", function() {
el.classList.remove(anotherClass);
}, true);`
Basically, what im trying to do:
Button click > Add class > When finished or interrupted by another button (and, therefore, new class), remove class or add the new
Obs.: I'm noob with JavaScript, so, please, do not explain with difficult words.
Try something simple:
function setSingleClass(el, singleClass)
{
if (!el._isSingleClassSet) {
el.classList.add(singleClass);
el._isSingleClassSet = 1
el.addEventListener("webkitAnimationEnd", function () {
el.classList.remove(singleClass);
el._isSingleClassSet = 0
}, true);
}
}
Updated: Narrowed this down even further eliminating the aspx JavaScript reference.
So it's down to this...if I uncomment the 1 line inside the init and remove the click event it behaves as expected. However, if I put the assignment statement inside my button click event I get the incorrect behavior as shown way down below.
<script type="text/javascript">
var pageDefault = {
btn1: document.getElementById('Button1'),
tdtarget: document.getElementById('targetTD'),
bg: document.getElementById('txtBGColor'), //jscolor textbox
init: function() {
//pageDefault.bg.value = pageDefault.tdtarget.getAttribute('bgcolor');
this.btn1.onclick = function() {
pageDefault.bg.value =
pageDefault.tdtarget.getAttribute('bgcolor');
}
}
}
pageDefault.init();
I am using jscolor. I am experience 2 different behaviors, one of which I don't understand.
All I'm trying to do is get the background color from a <TD> element of a <Table> and show the color value in a jscolor textbox.
pageDefault.bg.value = pageDefault.tdtarget.getAttribute('bgcolor').replace(/#/, '');
Found it on their website. I did look at it before but just had to narrow it down this far. Thanks for feedback and time (views).
pageDefault.bg.color.fromString('ffcc99');
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.