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.
Related
I'm trying to get each button that is appened to ('avatar-container comment ng-scope'), to be fully functional. Currently, only the top button is the button that is functional, and I'm not sure exactly why. Here's my code :
Also, I've already tried using addEventListener, but I was still running into the same problem :(.
$(document).ready(function () {
var groupcomments = $('.group-comments') // Container "Group Comments" are in
$(groupcomments).ready(function () {
function ucall(user) {
window.open('derp.com/userid=' + user, 'popup', 'width=600', 'height=600')
};
if (groupcomments[0]) {
var comments = groupcomments[0].getElementsByClassName('avatar-container comment ng-scope') // This gathers all of the comments themselves
$.each(comments, function () { // (you know this) but, this is looping over each comment.
var user = $(this).find('a')[0].href.toString();
user = user.replace(/[^\d]/g, '')
$(this).append('<button id=btnn>Click</button>') // using $(this) (which i assume are the comments, it appends the button to the comment)
var btn = document.getElementById('btnn') // getting the button
$(btn).click(function () {
ucall(user) // when button is clicked, call ucall function.
})
})
}
})
})
I commented in everything that should be useful, the button being appended worked, but it being clicked does not. Only on the first one appended. I'm just stuck right here.
You are adding a button <button id=btnn">Click</button> inside a loop. This means that you are adding several buttons all with the same ID. So, when you call document.getElementById('btnn'), you are only getting the first match in the list of buttons with the same ID.
You are only allowed to have one element with an ID. IDs are unique.
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 pagination div that contains links to the previous page <span id="previous"><a href="www.site.com/page/1" >Previous</a>, and to the next page. On the first page, there will not be any link to the previous page.
Now I have 2 image buttons with front and back arrows. If the user clicks on these buttons, jQuery will take the link from the pagination div as mentioned above and redirect the user to these links. However if the pagination link does not exist like on the first page, clicking the previous button will not do anything.
My Code:
//img has id = info_rightclick_left
$("#info_rightclick_left").click(function() {
if($("#pagination_previous")) {
window.location = $("#pagination_previous a").attr("href");
} else {
alert("NOO");
}
});
The problem now is that it seems like whether or not #pagination_previous exists, clicking the image still redirects the user. In this case, on page 1, the user gets redirected to undefined
How can I solve this?
Try this.
$("#info_rightclick_left").click(function() {
if($("#pagination_previous").length) {
window.location = $("#pagination_previous a").attr("href");
} else {
alert("NOO");
}
});
the answer in your question itself! just check for undefined like so:
$("#info_rightclick_left").click(function() {
if($("#pagination_previous a").attr("href") !== "undefined") {
window.location = $("#pagination_previous a").attr("href");
}
});
if($("#pagination_previous").length > 0) {
jQuery returns a list of captured elements, if it doesn't find any it will return an empty list, but still a list
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.
I have two DIVs, first one has a link in it that contains the id of the second DIV in its HREF attribute (complete setup on jsbin).
I want to animate the second DIV when user clicks on the first - anywhere on the first. I also want to use event delegation because I'll have many such "DIV couples" on a page (and I'm using a JS snippet from this SO answer).
If user clicks on the DIV itself, it will work - just check firebug console output. The problem is, if user clicks on one of the SPANs or the link itself, it doesn't work anymore.
How can I generalize the click handler to manage clicks on anything inside my DIV?
Here's the JS:
$('#a').click(function(e) {
var n = $(e.target)[0];
console.log(n);
if ( n && (n.nodeName.toUpperCase() == 'DIV') ) {
var id = $(n).find('a').attr('hash');
console.log(id);
$(id).slideToggle();
}
return false;
});
It took me so long to write up the question that I decided to post it anyway, perhaps someone suggests a better way.
Here's the solution I found (jsbin sandbox):
$('#a').click(function(e) {
var n = $(e.target)[0];
var name = n.nodeName.toLowerCase() + '.' + n.className.toLowerCase();
if (n && (name === "div.clicker" || $(n).parents("div.clicker").length )) {
var id = $(n).find('a').attr('hash');
if(!id) {
id = $(n).parents("div.clicker").find('a').attr('hash');
}
console.log(id);
}
return false;
});
Here is my solution. Not sure if that's exactly what you wanted, but it works for me.
$(document).ready(function() {
$('#a').click(function() {
var a = $("a", this);
$(a[0].hash).slideToggle();
});
});
Edit: Tested in both IE7 and Fx3
Edit: In that case...
$(function() {
$("a.tab").click(function() {
$($(this).attr("hash")).slideToggle();
return false;
});
});
Something like that might work (putting the tab class on anything that has a div "attached" to it). However, I'm not sure unless I actually see an example of it. Although if you want it to work when clicking on the span...you would attach the class to the span, and instead do:
$(function() {
$("span.tab").click(function() {
var a = $("a",this);
$(a.attr("hash")).slideToggle();
});
});
Not sure if you want an open div to close if another one is opened. If this doesn't solve your problem, it would help if you would put up an example on jsbin...