jQuery disable the previous span and the next span, on click span - javascript

I'm having trouble applying class to the previous element or the next element.
<a href="#"><span class="glyphicon glyphicon-thumbs-up up"></span>
<a href="#"><span class="glyphicon glyphicon-thumbs-down down"></span>
I want to disable the second span, when I click the first span and vice versa.
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(this).parent().nextAll('a.comment-vote-down');
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(this).parent().prevAll('a.comment-vote-up');
up.removeClass('disable-link').addClass('disable-link');
}
});
example on jsfiddle

You try to find class .comment-vote-down that doesn't exist in your HTML code
https://jsfiddle.net/xnovq390/4/

try this:
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(".down");
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(".up");
up.removeClass('disable-link').addClass('disable-link');
}
});

It's because you don't have an a with a class of .comment-vote-down, or comment-vote-up.
Either take that part out of your nextAll selection:
.nextAll('a');
https://jsfiddle.net/xnovq390/1/
or, add in the class to your HTML:
<a href="#" class="comment-vote-up">
https://jsfiddle.net/xnovq390/3/

If the .up element is always the previous element from the .down one, you can simply do:
$(document).on('click', '.up, .down', function(e) {
e.preventDefault();
if ($(this).hasClass('up')) $(this).next().addClass('disable-link');
else $(this).prev().addClass('disable-link');
}

$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
$(this).addClass('disable-link');
$('span.down').removeClass('disable-link');
}else if($(this).hasClass('down')){
$(this).addClass('disable-link');
$('span.up').removeClass('disable-link');
}
});

As the other answers already stated, there is no spoon element with .comment-vote-down class.
But additionally to make life easier, you could buffer the 2 elements, bind the click to them and disable the ones not clicked, reducing the code to
var btns = $('.up, .down');
btns.click(function(){
btns.not(this).addClass('disable-link');
});
fiddle
If you'd want to disable the containing a, the 'other's parent could be obtained by chaining parent() : btns.not(this).parent().addClass('disable-link'); ( or .closest('a') if there is a deeper hierarchy)

Related

Remove html element with javascript

When I press the Submit button if any error is generated then code create a span element.
My question is how I can clear the old error from the error container element, or if not possible then please sum up the errors.
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
I tried remove() but I cannot do it.
Thanks
you can remove the span with next().
next() finds the next sibling to the input field you are referring to.
it will give you the span:
el.next().remove();
you can use a class on the span f.e. class="validation-span"
el.next(".validation-span").remove();
this will make sure you only remove the span and no other element if existent :)
Add an span element after the input and set its HTML each time instead of using .after.
<input name="yourName">
<span class="errors"></span>
<script>
$(document).find('[name="'+i+'"] + .errors')
.html('<span style="color: red;">'+error[0]+'</span>');
</script>
I updated the both way you want, please pick which is more suitable to you
function logErrorCleanSpan(errorMessage){
$('#errorContainer').text(errorMessage);
}
logErrorCleanSpan("Hello");
logErrorCleanSpan("Jarvis");
function logErrorAppendSpan(errorMessage){
var span = $("<span>"+errorMessage+"</span>");
$('#errorContainerSpanAppend').append(span);
}
logErrorAppendSpan("1. Hello ");
logErrorAppendSpan("2. Jarvis ");
#errorContainerSpanAppend{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Append Error and clean the previous error<h3>
<span id="errorContainer"></span>
<h3>Append Error and keep the older one<h3>
<span id="errorContainerSpanAppend"></span>
Assign a id with index to span after each click remove previous span using id
Use jquery remove
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span id="error'+i+'" style="color: red;">'+error[0]+'</span>'));
if($(document).find('span#error+i - 1+')) {
$( "span#error+i - 1+" ).remove();
}
});
this is just an example code not correct code.

Removing Class Using Jquery According to Parameter Value

I have the following button link:
×
And the following js:
function reEnableBtn(prodId) {
alert(prodId);
};
Until now all good, on click of the link I get an alert with the content: 573 as expected.
Next thing I want to do is with the following html:
<a href="/new-page/?add-to-cart=573" class="button product_type_simple add_to_cart_button ajax_add_to_cart added" data-product_id="573">
<i class="fa fa-shopping-cart finished disabled-button"></i>
</a>
Within the JS I want to add a removeClass function which removes the classes 'finished' and 'disabled-button' from the <i> where the data-product_id of the parent <a> matches the value of prodId within the JS function (because I have other links with same structure but different data-product_id).
How do I do this?
You can
1) use attribute equal selector to target anchor element with same data product id
2) find element i in above anchor element
3) use removeClass to remove multiple classes from it
function reEnableBtn(prodId) {
$('[data-product_id=' + prodId + '] i').removeClass("finished disabled-button");
}
function reEnableBtn(prodId) {
$("a[data-product_id='"+prodId+"']").find("i").removeClass("finished disabled-button");
};
Use this simple script.
Use this code
jQuery(function($){
var s = $("body").find('[data-product_id=573]');
s.on("click", function(e){
var i = $(this).find('i');
if (i.hasClass('finished'))
i.removeClass('finished');
if (i.hasClass('disabled-button'))
i.removeClass('disabled-button');
alert("The classes was removed.");
return false; // this is for disabling anchor tag href
});
})
jsfiddle
If you have any other question feel free to ask in comments.

Hide a div if an element has been clicked twice in a row, else Show

I have several items in my navigation bar, and a div next to it, ie:
<nav>
<a id="a"></a>
<a id="b"></a>
<a id="c"></a>
</nav>
<div id="menu-col"></div>
If the same link is clicked twice in a row, I want to hide #menu-col. If not, I want #menu-col to remain visible.
I'm not a javascript guy so I tried this:
var lastClicked;
$('nav a').on('click', function(e) {
alert(e.target.id + " - " + this.lastClicked);
if (e.target.id == this.lastClicked) {
$('#menu-col').hide();
this.lastClicked = '';
}
else {
$('#menu-col').show();
this.lastClicked = e.target.id;
}
});
Then I remembered that javascript assigns references, and not values. So when I did this.lastClicked = e.target.id; I'm assigning a reference to my element's id, then on the next click I make that e.target.id == ''.
In javascript, what would be the proper way of closing a box if the same link is clicked twice, and if not making sure the box is visible.
You can achieve this using toggleClass() to set a state class on the clicked a and also using toggle() on the .menu-col to show or hide it based on that state class. Try this:
$('nav a').click(function(e) {
e.preventDefault();
var $a = $(this);
$a.toggleClass('active').siblings().removeClass('active');
$('.menu-col').toggle($a.hasClass('active'));
});
.menu-col {
display: none;
}
.active {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<a id="a" href="#">a</a>
<a id="b" href="#">b</a>
<a id="c" href="#">c</a>
</nav>
<div class="menu-col">menu-col</div>
As long as you keep those ids unique across you app (which you should be doing anyway) the approach you've chosen isn't wrong. Any primitive in javascript is actually stored by value. Those primitives are string, number, boolean, and symbol. For more info see here https://developer.mozilla.org/en-US/docs/Glossary/Primitive
I would suggest something like this, you should have some kind of condition in which the div shows after it has been hidden.
$('nav a').dblclick(function(event) {
event.preventDefualt();
alert($(this).attr('id'));
$('#menu-col').toggle();
});
Something like that should be exactly what you are looking for, like I said though, there should be a condition in which it shows itself again, I made it a toggle so any double click on any 'nav a' element will cause it to show/hide the div.
Just for the sake of an option. Here is another way for double clicks(clicked twice in a row).
Using ondblclick event.
Double-click me.

Can't figure out adding/removing classes with jquery

I need help with this JS code for my wordpress theme.
First part is when it looks for h4 heading and if it has certain text it wraps all paragraphs below this h4 into div (which hides all paragraphs into fading section) and adds "button" (which is span):
var tutustu = 'TUTUSTU';
var syvenny = 'SYVENNY';
$('.article_content h4').each(function(){
if($(this).text() == tutustu)
{
$(this).nextUntil("h4").wrapAll('<div class="expand" />').parent().append('<span id="expand">show more</span>');
}
else if($(this).text() == syvenny) {
$(this).nextUntil("h4").wrapAll('<div class="expand" />').parent().append('<span id="expand">show more</span>');
}
});
Second is when user clicks on "button" div (that we wrapped into all paragraphs early) will get another class (to basicaly reveal all the paragraphs) and remover button:
$('span#expand').click(function() {
$(this).parent('.expand').removeClass('expand').addClass('expanded');
$(this).remove();
});
What I need is after paragraph text is revealed I want to have button to click on and everything goes back like in 1st part.
I came up with something like this:
$('span#expanded').click(function() {
$(this).parent('.expanded').removeClass('expanded').addClass('expand');
});
But it doesn't work (
Help is much appreciated
Use event Delegation and .toggleClass() instead of .addClass() and .removeClass()
$(document).on("click" , "span#expanded" , function() {
$(this).parent().toggleClass('expanded expand');
});
$('#expanded').on('click', function(e) {
$(this).parent().toggleClass('expanded expand');
e.preventDefault();
});

JQuery Show/Hide Link

So here is my dilemma. Been trucking on this Jquery extreme code here and I need help telling if a certain link is showing or not. Here is what I have.
The toggles:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
(notice the only thing that is different is the icon number) These need to toggle back and forth when someone clicks the #visbilitybutton. Not sure of the best way to do this and to capture what is selected as well.
The only code I have currently makes the toggle go one way, but doesn't go back when clicked again.
$(document).ready(function () {
$('#visbilitybutton').click(function() {
$(this).replaceWith('<span class="icon icon85"></span>');
});
});
First things first, you shouldn't have multiple identical id attributes on your page. Make visibilitybutton a class.
Anyways, you can use the jQuery toggle() function to specify what to do on each consecutive click:
$(".visibilitybutton").toggle(function(){
$(this)
.attr("title","Invisible")
.find("span").toggleClass("icon84 icon85");
}, function(){
$(this)
.attr("title","Visible")
.find("span").toggleClass("icon84 icon85");
});
If you want to be more efficient, you can do it all in one fell jQuery swoop like so, with some good techniques:
var vis = ["Invisible","Visible"];
$(".visibilitybutton").click(function(){
var i = 0;
$(this)
.attr("title",vis[i])
.find("span").toggleClass("icon84 icon85");
i = (i==0)?1:0;
});
Even more so would be to make a class that hides the element when added to it and shows it when you remove it (a classname with display:none applied in the CSS works fine):
$(".visibilitybutton").click(function(){
$(this)
.toggleClass("hide")
.find("span").toggleClass("icon84 icon85");
});
You need to have unique ids; therefore, you should select the items by class. You can use toggle() to handle the consecutive clicks, and you can use toggleClass() to handle the swapping of classes.
HTML:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
Javascript:
$(document).ready(function () {
$('.button').toggle(function() {
var $button = $(this);
$button.prop("title","Invisible");
$button.find('.icon85').toggleClass('icon85', 'icon84');
}, function() {
var $button = $(this);
$button.prop("title","Visible");
$button.find('.icon85').toggleClass('icon84', 'icon85');
});
});
The id attribute is supposed to be unique to each element. Change the id attribute to the class attribute for each hyperlink.
Then, in your jQuery code, get the hyperlinks by their class name:
$('.visbilitybutton').click(function() {
// code goes here
});
In your event handler, you should use test the title attribute, like so:
$('.visibilitybutton').click(function() {
$this = $(this);
if ($this.attr("title") == "Visible")
$this.attr("title", "Invisible").find("span")
.removeClass("icon85").addClass("icon84");
else
$this.attr("title", "Visible").find("span")
.removeClass("icon84").addClass("icon85");
});

Categories

Resources