How to build a jQuery-powered switcher to add/remove css attributes? - javascript

I'm trying to build a box container that expands when clicking in a "read more" button and collapse to the initial size when clicking in the same button (now a "collapse" button).
In the DOM I have a .leer-mas button inside a .post container. And the following jQuery code:
//When link with class .leer-mas is clicked, get the parent element's id and add some css attributes
$('.leer-mas').click(function() {
var item = $(this).closest('.post');
item.css('height', 'auto');
$(this).addClass('leer-menos');
$(this).text('Leer menos');
});
//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$('.leer-mas.leer-menos').click(function() {
var item = $(this).closest('.post');
item.removeAttr('height');
$(this).removeClass('leer-menos');
})
The first action works like a charm. But the second action does nothing... And I think I'm missing some fundamentals of jQuery, as the syntax is identical and maybe that is not the way it should be :)
Any ideas? Thanks.
Edit - I had a few errors on my code. Though I'm still trying to get it with a single switcher, I have a working version.
New DOM looks like this:
<div class="post">
<div class="leer mas">
</div>
<div class="leer menos">
</div>
</div>
The code now looks like this:
//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.mas').click(function() {
var item = $(this).closest('.post');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
item.css('height', 'auto');
$(this).hide();
$(this).next('.leer.menos').show();
});
//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.menos').click(function() {
var item = $(this).closest('.post');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
item.removeAttr('style');
$(this).hide();
$(this).prev('.leer.mas').show();
});
This works smoothly. But If I get it working with the intended structure of the original question (with a single button), i would be happier :)

it is because the class leer-menos is added dynamically... so when the event registration code is executed there is no element with classes leer-mas and leer-menos.
A possible solution is to use event delegation
//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$(document).on('click', '.leer-mas.leer-menos', function() {
var item = $(this).closest('.post');
item.removeAttr('height');
$(this).removeClass('leer-menos');
})

You're trying to use .removeAttr() to remove a CSS Property within the attribute "Style". This is incorrect, try using item.removeAttr('style');

Not exactly what you asked for, but you can draw ideas from this:
$('.leer-mas').click(function() {
var item = $(this).closest('.post');
// toggle "height" between 'auto' and null
item.css('height', item.css('height') == 'auto' ? null : 'auto' );
// toggle class 'leer-menos'
$(this).toggleClass('leer-menos');
// toggle text between 'Leer menos' and ''
$(this).text( $(this).is('.leer-menos') ? 'Leer menos' : '' );
});

Related

Add class to anchor-link on other page

I've got a navigation set up with links to anchors on specific page.
This works when on that specific page, but how can I add the class when coming from another page on my site?
<script>
jQuery(function ($) {
$( document ).ready(function() {
$(".sub-menu > li > a").on("click", function(){
$("a.active").removeClass("curlink");
$(this).addClass("curlink");
});
});
});
</script>
Simply pass one more hidden input element say with id navigator
when you are clicking on a link with id #a1 then set this hidden element value to "a1"
Send this element with form
On receiver page check for value of this element say $("#navigator").val();
On the basis of the value of this, which is "a1" in this case, set CSS of link with id a1 whatever you want, using $("#a1").css();
Another method is that on every hyperlink add a GET parameter and receive on the receiver side and on the basis of its value set CSS.
Let's say there are 3 links with id a1,a2,a3
Add a parameter say cameFrom in href URL e.g. href=".../*.html?cameFrom=a1" for link a1 and href=".../*.html?cameFrom=a2" for link a2 and so on
On receiver page get its value by using this function:
function param(name){
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
Use param(cameFrom) and get result.
Link to this function
There are many ideas/ways to achieve this, but if you have separate file which contains navigation code then you can do one way,
you can put in a hidden element with value of id of the <a> tag of menu of navigation. So when you land on the page and found that id value from the hidden field in jquery, you can make that <a> of navigation activated. I mean you can apply active class to that menu.
Tell me if this is not clear, I would try to make it simple.
In simple words,
Add one hidden element in your separate pages like <input type="hidden" value="about_us" id="nav-menu">
And in your master page,put jquery to get this value like:
var nav_menu = $('#nav-menu').val(); so in nav_menu you will have about_us as its value.
Now, in main master view file, you can write jquery to add active class for relevant manu like: $('.sub-menu > li > a').removeClass('active');$('#'+nav_menu).addClass('active');

How to change button class in a div while just the last one can keep the change?

I'm using this code to change my buttons's class:
$('button').on('click', function(){
var btn=$(this);
if(btn.attr('class')=='tct-button'){
btn.removeClass('tct-button').addClass('tct-button2');
}
else{
btn.removeClass('tct-button2').addClass('tct-button');
}
});
The problem is that I have multiple div's with multiple buttons in each. I need to change this so that every time I click on a button in a div the others which were changed by a previous click (in that same div) change back to the default class which is 'tct-button', and just the last clicked button turns to 'tct-button2'. Would you please help me.
use toggleClass in jquery ,there is no need to check hasClass()
$(this).toggleClass("tct-button2 tct-button");
DEMO
Use hasClass()
Determine whether any of the matched elements are assigned the given class.
Code
$('button').on('click', function(){
var btn=$(this);
if(btn.hasClass('tct-button')){
btn.removeClass('tct-button').addClass('tct-button2');
}
else{
btn.removeClass('tct-button2').addClass('tct-button');
}
});
However I think you need
$('button').on('click', function(){
$('.tct-button2').removeClass('tct-button2'); //Remove all class
$(this).addClass('tct-button2'); //Add the class to current element
});
If you want to add an additional class to your buttons (tct-button2) whilst keeping tct-button on every button you could do what Satpal suggested.
However, from the sounds of it and I may be wrong, if you want to change the classes so that each button only has one class at a time on it (either tct-button or tct-button2) you can do similar to what Satpal suggested and use:
$('button').on('click', function(){
$('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Add original class and Remove tct-button2 class
$(this).removeClass('tct-button').addClass('tct-button2'); //Add the class to current element
});
Here is the example http://jsfiddle.net/lee_gladding/xao46uzs/
to only affect buttons in the div the clicked one belongs to, use a similar method to:
$('button').on('click', function(){
$(this).parent('div').find('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Remove all class in that div
$(this).removeClass('tct-button').addClass('tct-button2'); //Add the class to current element
});
(You might want to use a better selector for the parent, possibly a class or what ever your actual html uses)
Example:
http://jsfiddle.net/lee_gladding/xao46uzs/3/

Element not reacting to JQuery Click

I have added Elements using Jquery inside PHP after loading them from the database. Each button has two classes, one controlling the GUI and another controlling the Click for particular button. The code is as under
echo "<script type='text/javascript'>$('.main').append('<button class=b_ui b$index>Change</button>'); </script>";
Now if I check the classes from Inspect Element perspective of the browser, it shows 2 classes. But when I click on it and get class of element using this code
$('.b_ui').click(function()
{
cls = $(this).attr('class');
alert('no. '+cls);
}
It shows only first class (GUI) and not the other which I want to use for handling click.
Any help ?
Put quotes around the class attribute. <button class=\"b_ui b$index\">Change</button>
You should use "on" method:
$(document).on('click', '.b_ui', function() {
cls = $(this).attr('class');
alert('no. '+cls);
});
When adding elements dynamically to the DOM, they are not accessible by jQuery like an element which was there at page load. say you have this div:
<div id="div"></div>
and you add some content with jQuery so it now looks like this:
<div id="div"><span id="span"></span></div>
you cannot refer directly to the span using jQuery with $('span[id=span]'), you have to target a containing element then filter which contained element you want:
$('#id').on('click','span',function(){});

Creating a "selected item" javascript code for navigation menu?

I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?
$('#Button1').click(function(){
$('#Button1').addClass("selectedItem");
$('#Button2').removeClass("selectedItem");
$('#Button3').removeClass("selectedItem");
$('#Button4').removeClass("selectedItem");
$('#Button5').removeClass("selectedItem");
$('#Button6').removeClass("selectedItem");
$('#Button7').removeClass("selectedItem");
$('#Button8').removeClass("selectedItem");
$('#Button9').removeClass("selectedItem");
$('#Button10').removeClass("selectedItem");
});
You could try something like this -
$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1
You could also simply bind all the elements with the same handler like this -
var $buttons = $("[id^='Button']");
$buttons.on('click', function ()
{
$buttons.removeClass("selectedItem");
$(this).addClass("selectedItem");
});
For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.
Checkout the Attribute Starts With Selector [name^="value"] selector.
I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:
var $buttons = $('.button').on('click', function() {
$buttons.removeClass('selectedItem');
$(this).addClass('selectedItem');
});
Meta example: http://jsfiddle.net/88JR2/
You could have a class .button and apply it to all your buttons then
$('#Button1').click(function(){
$('.button').removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
});

jQuery toggle method issue

When using jquery-ui-1.8.15.custom.min toggle method, the element next to the target element is always hidden.
Here is the test page: http://jsfiddle.net/dassio/CLrMx/9
I want the div with class name suggestion to toggle between hidden and show when you click the button, but why the red line is always missing?
This should do the job:
http://jsfiddle.net/CLrMx/15/
Your script was accidentally hiding your text. Cleaned it up a bit so it olny does the necessary.
I found the problem:
<div id="config" class='name ui-widget-content ui-corner-all'>
<button id="details">show details</button>
</div>
I add the name class name to the parent div around the button, and when the event bubble up to the parent div, the following code:
$(".name" ).click(function() {
var clicked = $(this);
var suggestion = clicked.next();
suggestion.toggle("fold",200);
return false;
});
was called and toggle off the <h3> element which is the next element of the parent div.

Categories