How can I combine .toggleClass() with .appendTo()? - javascript

I append a new class to a HTML container. How can I toggle this on/off by clicking on the menu button?
And is it even "best practice" to write more complex HTML code in JavaScript or would you prefer another method for this? Because I plan to do this for some more containers. Thank you!
$(document).ready(function() {
$( "a.header-login" ).click(function() {
$("<div class='sub-menu'>" +
"<h2>Hi x!</h2>"+
"<a class='item' href='#'>Logout</a>"+
"</div>")
.appendTo("header .header-r");
})
});

I want to accomplish that another click on "a.header-login" deletes the container ".sub-menu". Now, it is always generated when you click "a.header-login"
In this case you need to add a condition to check whether or not the element already exists. If it doesn't create it, if it does remove it.
jQuery(function() {
$('a.header-login').click(function() {
var $target = $('header .header-r .sub-menu');
if ($target.length === 0) {
$('<div class="sub-menu"><h2>Hi x!</h2><a class="item" href="#">Logout</a></div>').appendTo('header .header-r');
} else {
$target.remove();
}
})
});
That being said, you can make this much simpler logic if you always include the .sub-menu in the HTML of your page but hide it with CSS by default. In that case your jQuery would become a simple call to toggle():
jQuery(function() {
$('a.header-login').click(function() {
$('header .header-r .sub-menu').toggle();
})
});

Related

JQuery not removing active class

I'm trying to make my links slide down over the page when the mobile nav is clicked and the content to disappear so only the links are shown. I have got this basically working but the .displayNone class will not remove when I click the mobilenav again and I'm a bit dumfounded as to why.
$(document).ready(function() {
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('.displayNone');
if(status){ $('.wrapper').removeClass('.displayNone'); }
else { $('.wrapper').addClass('displayNone'); }
});
});
Bit of newbie to all this. Anything obvious that anyone can see wrong with this?
Use toggleClass(),
$('.wrapper').toggleClass('displayNone');
And, jQuery's xxxClass() functions expect the name of the class, not the selector, so leave off the . class selector.
When adding/removing classes, just use displayNone, not .displayNone (note the dot!).
Also there's a toggleClass() function which saves you from doing the status thing, which means you just need to do
$('.wrapper').toggleClass('displayNone');
your are doing bit wrong
var status = $('.wrapper').hasClass('.displayNone');
when you use hasClass, addClass or removeClass then you don't need to have '.' dot before class name.
so correct way is
var status = $('.wrapper').hasClass('displayNone');
your code after correction
$(document).ready(function() {
$('#hamburger').on('click', function() {
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('displayNone');
if (status) {
$('.wrapper').removeClass('displayNone');
} else {
$('.wrapper').addClass('displayNone');
}
});
});
You can use :
$('.wrapper').toggleClass("displayNone");
Final code :
$(document).ready(function(){
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
$('.wrapper').toggleClass("displayNone");
})
})

Tabs that switch multiple elements

I really stuck on this, what I need is to switch the image together with the tabs text, but the image should be outside of the tabs container. I made some jQuery code, but it's not flexible in case if I want to add more tabs and the functions are duplicating, which is also looks not so well.
Is there some option, maybe a function that will check if the number of cliked tab will match with image id and switch the image according this number.
Please help :)
The code example - http://codepen.io/DeoThemes/pen/EyAjVA
jQuery:
$('#tabs-img-1').show();
$("a[href='#tab-1']").on('click', function() {
$('.tabs-img').hide();
$('#tabs-img-1').show();
});
$("a[href='#tab-2']").on('click', function() {
$('.tabs-img').hide();
$('#tabs-img-2').show();
});
$("a[href='#tab-3']").on('click', function() {
$('.tabs-img').hide();
$('#tabs-img-3').show();
});
$("a[href='#tab-4']").on('click', function() {
$('.tabs-img').hide();
$('#tabs-img-4').show();
});
$("a[href='#tab-5']").on('click', function() {
$('.tabs-img').hide();
$('#tabs-img-5').show();
});
This will do without changing any of your code. Let me know your feedback. Thanks!
$('.tabs a[data-toggle="tab"]').on('click', function() {
$('.tabs-img').hide();
$('#tabs-img-' + $(this).attr('href').split('-')[1]).show();
});
or better still you can place an attribute on the a tag which will be the id of the tab!
I have edited your Codepen.
Add custom attribute to anchor link:
Business Oriented
And then change your script to this:
$("ul.nav-tabs li a").on('click', function() {
$('.tabs-img').hide();
$($(this).attr('imgId')).show();
});

Moving elements from a list to another list with JQuery

I would like to add an element to another list and remove it from the current when clicked. I tried it with the property appendTo of Selectable, but nothing happens when I click on it.
I built this https://jsfiddle.net/wgaga8uc/ to ilustrate it.
$("#paramselectable").selectable({appendTo: "#paramselected"});
$("#paramselected").selectable({appendTo: "#paramselectable"});
I would appreciate any help,
Thanks.
$("#paramselected li").click(function(){
$("#paramselectable").append(document.createTextNode( "Hello" ));
});
Finally I achieved it adding and removing classes. https://jsfiddle.net/22d7sxvd/
$(function() {
$( ".paramsnav" ).selectable();
});
$('li').click(function () {
var selected = $('#params').find('.ui-selected');
if(selected.hasClass('selectable')) {
selected.removeClass('ui-selected');
selected.removeClass('selectable');
selected.addClass('selected');
selected.appendTo('#paramselected');
} else {
selected.removeClass('ui-selected');
selected.removeClass('selected');
selected.addClass('selectable');
selected.appendTo('#paramselectable');
}
});

adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.
HTML:
<div id="mainNav">
<ul id="nav">
<a id="mainLogo" href="/"><li></li></a>
<a id="aboutLink" class="aLink" href="/"><li></li></a>
<a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
<a id="external" href="/"><li></li></a>
</ul>
</div><!--/#mainNav-->
I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.
jQuery:
$(function () {
$(".aLink").click(function () {
if ($(this) == $("#aboutLink")
$(this).addClass('activeLink');
else $(this).addClass('active2Link');
});
});
Thanks for any input or direction.
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(){
e.preventDefault();
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
You could, instead, use toggleClass() to allow for those classes to be removed by a second click:
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(e){
e.preventDefault();
$(this).toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
Edited in response to question, from the OP, in comments, below:
How would I remove the class so that both links don't appear to be active at the same time?
There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:
$('#nav a').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('ul').find('a[class]').attr('class', '');
self.toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:
$('#nav a').click(function(e){
e.preventDefault();
for (var id in idToClass) {
if (idToClass.hasOwnProperty(id)){
$('#' + id).removeClass(idToClass[id]);
}
}
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
If, of course, you use a common class-name then it all becomes much easier:
$('#nav a').click(function (e) {
e.preventDefault();
var self = $(this);
self.closest('ul')
.find('.commonActiveClassName')
.removeClass('commonActiveClassName');
self.addClass('commonActiveClassName');
});
JS Fiddle demo.
References:
addClass().
closest().
event.preventDefault().
find().
removeClass().
toggleClass().
Since you already have ID tags to easily reference... I think you want something more like this?
$(function () {
$("#aboutLink").click(function () {
$(this).addClass('activeLink');
});
$("#sasLink").click(function () {
$(this).addClass('active2Link');
});
});
Try using this instead:
$(function () {
$(".aLink").click(function () {
var currentId = this.id;
if ( currentId == "aboutLink"){
$(this).addClass('activeLink');
else if( currentId == "sasLink") {
$(this).addClass('active2Link');
}
});
});

What is the best way to user jQuery selector at this problem?

I really don't know what would be the best title for this. Basically, on my page I have a dropdown menu which is implemented by jQuery (.slide). The dropdown appear in both at the top and bottom of the page, so it's easier for user to scroll down and can still use the dropdown menu. The page to display this I use rail partial so that I can refactor it quite easy.
The problem is, since the two dropdown menus are in the same page, so they can't not have the same ID but they have the same functionality, when the user click then opens up and show other options. What is the best way to let them use the same logic but different id and less code as possible.
I don't want to do something like this.
$('.sub_export_record1').hide();
$('.export_record_link1').click( function(e) {
e.preventDefault();
});
$('.export_record1').click( function(e) {
if ( $(".sub_export_record1").is(":hidden") )
{
$('.sub_export_record1').slideDown("slow");
}
else
{
$('.sub_export_record1').hide();
}
});
And then the second one
$('.sub_export_record2').hide();
$('.export_record_link2').click( function(e) {
e.preventDefault();
});
$('.export_record2').click( function(e) {
if ( $(".sub_export_record2").is(":hidden") )
{
$('.sub_export_record2').slideDown("slow");
}
else
{
$('.sub_export_record2').hide();
}
});
Thanks a lot. :)
HTML
<ul>
<li class="export_record">
<%= link_to "Export this Record"%>
<ul class="sub_export_record">
<li><%= link_to "Export to Photo Wall"%></li>
<li><%= link_to "Export to PDF"%></li>
<li><%= link_to "Export to CSV"%></li>
</ul>
</li>
</ul>
There is no need to identify the elements. Give them the same class (as you already have in the snippet):
$('.sub_export_record').hide();
$('.export_record').click( function(event) {
event.preventDefault();
var $sub = $(this).children(".sub_export_record");
if ( $sub.is(":hidden") ) {
$sub.slideDown("slow");
}
else {
$sub.hide();
}
});
Give same class and different ID and then use something like this:
Suppose the class name is export_record. You can give different ID to each menu and check which element is clicked.
$('.export_record').click( function(e) {
e.preventDefault();
$('.export_record').hide();
$(this).slideDown("slow");
if($(this).attr("id") == "THE_ID_YOU_GAVE_TO_ELEMENT"){
/* Do operation for that specific element. */
}
});
You could do this:
$('.sub_export_record').hide();
$('.export_record_link').click( function(e) {
e.preventDefault();
});
$('.export_record').click( function(e) {
var $sub = $(this).find(".sub_export_record"); //This is the key
if ($sub.is(":hidden") )
$sub.slideDown("slow");
else
$sub.hide();
});
With this, you can have the same html for both widgets and only 1 javascript code.
Hope this helps. Cheers
Just hook up the same event handlers to both elements. Use parent IDs to directly address each object for the purposes of hooking up the event handlers. For purposes of this illustration, I just assumed that the top menu is contained inside a div with an id of header and the bottom div with in id of footer, but you can use any CSS selector that uniquely targets each one.
$('#header .sub_export_record').click(handleExportClick);
$('#footer .sub_export_record').click(handleExportClick);
function handleExportClick() {
var $obj = $(this);
if ($obj.is(":hidden")) {
$obj.slideDown("slow");
} else {
$obj.hide();
}
}
Several comments :
you could use id with multiple selectors, you would have something like :
$("#sub1, #sub2").hide();
$("#sub_export1, #sub_export2").click()...
you cannot use multiple click functions, you will have to merge all your functions into the click one [Edit] i was wrong as Felix pointed out
Regards,
Max

Categories

Resources