Why is my click function not addClass or removeClass - javascript

this is my markup, from my sublayout:
<div class="main-nav">
<a id="tabmovies" href="#" class="main-nav-tab active">Movies</a>
<a id="tabtheatres" href="#" class="main-nav-tab">Theatres</a>
</div>
</div>
and this is my .js ... which the alert indicates the click function is working
// Toggle between movies and theatres
$("#tabmovies").click(function () {
alert("you have clicked movies");
$("tabmovies").addClass("active");
$("tabtheatres").removeClass("active");
});
$("#tabtheatres").click(function () {
alert("you have clicked theatres");
$("tabmovies").removeClass("active");
$("tabtheatres").addClass("active");
});
but the class "active" is not being added or removed. Am I missing something?

To select an element by ID in jquery use "#theID" as selector.
Change
$("tabtheatres").addClass("active");
to
$("#tabtheatres").addClass("active");

Try this,
$("#tabmovies").click(function() {
alert("you have clicked movies");
$("#tabmovies").addClass("active");
$("#tabtheatres").removeClass("active");
});
$("#tabtheatres").click(function() {
alert("you have clicked theatres");
$("#tabmovies").removeClass("active");
$("#tabtheatres").addClass("active");
});
You need to add # before the id selector.
FIDDLE DEMO

Change your code as following:
// Toggle between movies and theatres
var $tabmovies = $("#tabmovies"),
$tabtheatres = ("#tabtheatres")
$tabmovies.click(function () {
alert("you have clicked movies");
$tabmovies.addClass("active");
$tabtheatres.removeClass("active");
});
$tabtheatres.click(function () {
alert("you have clicked theatres");
$tabmovies.removeClass("active");
$tabtheatres.addClass("active");
});
DEMO
You are not selecting anything because you should specify selector correctly. In case of id selector use # symbol. For class selector use . Learn about jquery selectors here. And avoid multiple queries in your code. Select once and use reference many time. It will give you performance gain.

Related

Click event on a link with a unique id

On a page I have links, by clicking them, it deletes an element. This is my code:
Delete input
Delete input
and so on. As you can see, the links differs with ids, so there can be hundreds links with unique ids. I need to remove closest li element to them. I do it in a such way:
$(document).ready(function () {
$('#link0').click(function (e) {
e.preventDefault();
$(this).closest('li').remove();
})
});
It works for id="link0"
I tried to put a numerical part of id into a variable i by doing this:
var i = 0;
$('#link0' + i).click(function (e) {
e.preventDefault();
$(this).closest('li').remove();
})
but I can't figure, how to make it work and how should I increment i(where should I put in the code i++). Any help would be appriciate. Thanks!
You can use classes instead of ids...
You can do it like this:
$(document).ready(function() {
$('.remove-existed-field').on('click', function(e) {
$(this).closest('li').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>Delete input</li>
<li>Delete input</li>
Hope this helps!
You could use the starts with selector.
$('[id^=link]').click(
It will target all the elements whose id start with link
If you want to process each link a then you could do it on class instead.
Also you can get id of the clicked link if you really need it.
$(document).ready(function () {
$('a.remove-existed-field').click(function (e) {
e.preventDefault();
// $(this).attr('id');
$(this).closest('li').remove();
});
});

add and remove class on same button or element

I'm looking for a way to add and remove class on the same button. So far this is my work in progress. The concept is when I click on the menu button it shows the menu. When I tap on the menu button again. The menu hides
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$('.portfolio-contact-form-wrap').addClass('show');
});
});
To achieve this you can use .toggleClass() like so:
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$('.portfolio-contact-form-wrap').toggleClass('show');
});
});
JsFiddle example
toggleClass
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added.
For more information about this function check here
Hope this helps!
You should use $(this) and toggleClass
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$(this).toggleClass('show');
});
});
which will add the class back to the specific element that was clicked.
http://api.jquery.com/toggleclass/
http://www.learningjquery.com/2007/08/what-is-this
Try this:
$(document).ready(function(){
$('button.toggle-portfolio').on('click', function(e){
$('.portfolio-contact-form-wrap').toggleClass('show');
});
});
DEMO
$('.toggle-portfolio').on('click', function(e) {
$('.portfolio-contact-form-wrap').toggleClass('show');
});
Try this way
You can use .add() method with .toggleClass():
$(document).ready(function() {
$('button.toggle-portfolio').on('click', function(e) {
$('.portfolio-contact-form-wrap').add(this).toggleClass('show');
});
});
.portfolio-contact-form-wrap {
color:blue;
}
.show {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="toggle-portfolio">Button</button>
<div class="portfolio-contact-form-wrap">
<h1>contact form</h1>
</div>
Use toggleClass('show')
It will add the class on one click and remove the class on the second click.
<script>
$(document).ready(function () {
$('button.toggle-portfolio').on('click', function (e) {
$('.portfolio-contact-form-wrap').toggleClass('show');
});
});
</script>

javascript jquery accessing the element being clicked

I've got the following list of semibuttons loaded using javascript:
var html ='<ul class="nav well-tabs well-tabs-inverse mb10" id="users">';
html +='<li class="active"><a id="'+this.my.user+'" data-toggle="tab_'+self.my.id+'" class="pestaƱa">'+this.my.user+'</a></li>';
var users = this.my.community_users;
for (i=0;i<users.length;i++) {
if (users[i].user != this.my.user)
html +='<li><a id="'+users[i].user+'" data-toggle="tab_'+self.my.id+'" class="pestana">'+users[i].user+'</a></li>';
};
html +='</ul>';
$(html).appendTo("#Dashboard");
Note, that the first item in the list is active. I am getting something like this:
Ok, now i code he onclick event to do something when a button is clicked:
$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function(e){
// whatever here
});
What I need now is to set active the tab being clicked and set inactive the tab that was active. How can I access both elements to addclass and removeclass active?
You could use following logic:
$(document).on('click', '#users li:not(.active)', function () {
$('#users').find('li.active').add(this).toggleClass('active');
});
Something like this might work. Basically remove the .active class from everything but the element you clicked on. The add the .active class to the element clicked on.
$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function (e) {
$('a[data-toggle=tab_'+self.my.id+']').not(this).removeClass('active');
$(this).addClass('active');
});
I would remove the 'active' class from all the list items first, then add it back to just the only that was clicked.
$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function (e) {
$('#users .active').removeClass('active');
$(this).addClass('active');
});

jQuery get css value of clicked link or tell which link was clicked

I've got links on my page like this, which when clicked, call jQuery functions. How can I tell if approve was clicked or delete was clicked. Because I need to do certain things only if accept was clicked, and need not do things if delete were clicked. I cannot change the way those links are named.
<i class="icon-accept blue approve"></i>
<i class="icon-reject blue delete"></i>
$('.approve,.delete').on('click', function() {
if(approved was clicked) {
console.log('Approve was clicked');
}
});
You can check the class using hasClass():
$('.approve,.delete').on('click', function() {
if($(this).hasClass('approve')) {
console.log('Approve was clicked');
}
});
jsFiddle Demo
Alternatively, you can use is():
$('.approve,.delete').on('click', function() {
if($(this).is('.approve')) {
console.log('Approve was clicked');
}
});
jsFiddle Demo
You can use jquery .is():
if($(this).is('.approve')){}
try
$(element).hasClass('className')
You can use .hasClass()
$('.approve,.delete').on('click', function() {
if($(this).hasClass('approve')) {
console.log('Approve was clicked');
}
});

How to toggle the link in my case?

I am trying to toggle a link texts and content when user clicks the link.
I have something like
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
})
When user click the link, the link text will become isClicked and the items html will be replaced with a image. However, if user clicks again, I want to see the link text changes back to click me and the items will hide the image and display the title and p tag contents again.
I am not sure how to accomplish this. Can anyone help me about it? Thanks a lot!
You can add a dummy class to the link and work with that condition
//Have a dummy class added to the link and toggle it on click
$('#link').on('click', function(e){
e.preventDefault();
var $this = $(this),
$textDiv = $('#items'),
$imageDiv = $('#image')
if($this.hasClass('clicked')) {
// remove the class
$this.removeClass('clicked');
// change the text
$this.text('click me');
// Hide image
$imageDiv.addClass('hide');
// show text
$textDiv.removeClass('hide');
} else {
// remove the class
$this.addClass('clicked');
// change the text
$this.text('isClicked');
// Show image
$imageDiv.removeClass('hide');
// Hide text
$textDiv.addClass('hide');
}
});
Check Fiddle
You can also chain the methods applied on the same element.
$('#link').on('click', function(e){
e.preventDefault();
if ($(this).text() == "isClicked") {
$(this).text("click me");
.. etc
} else {
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
}
});
Like I said in my comment, use a condition like this. Simple and effective.
One way you could do it:
$('#link')
// Set data attribute to hold original text
.data('primeText', $('#link').text())
// set click event using jQuery1.73+
.on('click', function(e) {
e.preventDefault(); // prevents going to link, not needed if you set link href to "javascript:void(0)"
// begin setting text, within is a inline-if statement testing current text against prime text
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Another way, if you were working with more than one, like using a class name instead of ID:
$('.link')
// jQuery's .each method allows you to do things to each element in an object group
.each(function(i) { $(this).data('primeText', $(this).text()); })
// again, calling click method
.on('click', function(e) {
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Examples
What about using a CSS approach?
Your HTML would stay the same:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
But we can use .toggleClass() here to make our lives easier
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').toggleClass('display-image');
})
The CSS would look like:
#items.display-image > h1,
#items.display-image > p,
{
visibility:hidden;
}
#items.display-image{
background-image:url("/images/image.png");
}
This way, you don't have to worry about removing things and .toggleClass handles their visibility.
You might have to do additional styling to get the image to work properly, or you may consider adding another element to contain the image and you can just set its visibility or display property
Try something like this:
HTML:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1 class="text-item">title here</h1>
<p class="text-item">texts here...</p>
<img src="images/images.png" alt="Image" />
</div>
CSS:
img {
display: none;
}
JavaScript:
$('#link').off().on('click', function(e) {
e.preventDefault();
if($('#items > img').is(':visible')) {
$(this).text('click me');
$('#items > img').hide();
$('#items > .text-item').show();
} else {
$(this).text('isClicked');
$('#items > .text-item').hide();
$('#items > img').show();
}
});
Fiddle
You can try to store the value in a var and then toggle with on off in functions themselfs;
var initialState = $('#items').html(),
functionBla(e) {
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
$('#link').off('click').on('click', functionCla);
},
functionCla(e) {
e.preventDefault();
$(this).text('click');
$('#items').html(initialState);
$('#link').off('click').on('click', functionBla);
};
$('#link').on('click', functionBla);
You can do it like,
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').children().toggle();
var img=$('#items img');
if(img.length>0){
img.remove();
}
else{
$('#items').append("<img src='images/image.png' />");
$(this).text('Click me');
}
})

Categories