JQuery to add <body> class, need a little more help - javascript

I have this snippet of code to parse the URL and add a class to the <body>tag of my HTML page.
var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, " ");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace(" ","");
var newClass = pathSlashesReplacedNoFirstDash.replace(/(\.[\s\S]+)/ig, "");
$("body").attr("class",newClass);
if ( $("body").attr("class") == "")
{
$("body").addClass("class");
}
The issue I am having is that it deletes existing body classes already there. Instead, I would like to append to whatever body classes exist and not overwrite.

Use this:
$("body").addClass(newClass);
instead of
$("body").attr("class",newClass);
This is a setter: $("body").attr("class",newClass); which sets the class to the newClass and does not append it.

Use addClass instead of attr('class', newClass). The addClass also accepts a white-space separated list of class names, and correctly adds them.
$("body").addClass(newClass);
if ( $("body").attr("class") == "") // Makes no sense, since you have previously
{ // added `newClass`
$("body").addClass("class");
}
For documentation on addClass, see http://api.jquery.com/addClass/

.attr("class", newClass) is removing all existing classes. You should be using .addClass() instead:
$("body").addClass(newClass);
In addition, since you've just added a class to body, the code below will always be false:
if ( $("body").attr("class") == "") { }

Use addClass function instead - http://api.jquery.com/addClass/

Related

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Modify class defined by var on a function

I want to add class "unblock" to all elements contanining desbloquear var value (in this case, taken from clicked a element's id).
I am not able to do this... as there are several ements that should receive the new class, I can not set the same id to them (to be equal as "a" id). How could I say, on the last line of the function, that all items containing "a" class (desbloquear var value) should add class unblock?
I've tried
$(.desbloquear).addClass('unblock');
and
$(".desbloquear").addClass('unblock');
without result...
$('a').on('click', unblock);
function unblock(){
var desbloquear = $(this).attr('id');
$(desbloquear).addClass('unblock');
}
all items containing "a" class (desbloquear var value) should add class unblock
I might not got your question correctly but by above line. It looks that you want to add a class unblock to elements those have some specific class. if yes then you can do like this
function unblock(){
var desbloquear = $(this).attr('class');
$('.'+ desbloquear).addClass('unblock');
}
Yes you are correct, Id's should be unique, you can use class instead
You will need a . to specify a class attribute in selector
$('.'+desbloquear).addClass('unblock');
class selector should begins with a .
Just try,
$('.' + desbloquear).addClass('unblock');
Full code:
$('a').on('click', unblock);
function unblock() {
var desbloquear = $(this).attr('id');
$('.' + desbloquear).addClass('unblock');
}

dynamic class select in javascript

I want to write a function in jquery using handlebars. where name of html and class where it has to be appended will be pass dynamically.
Basically i need something like this :
var pageTemplate="";
function addTempl(){
var renderedPage = pageTemplate(pageName);
$("#Class_id").empty();
$("#Class_id").append( renderedPage );
}
this Class_name and pageName will be dynamically passed to this function from another main function where it will be called.
Issue is i can pass pageName as it is javascript thing but how to do same for Class_name. beacuse if I append '#' and "" it is not coming.
please let me know if my problem is still unclear.
class is denoted by . and id is denoted by #
updated
$("#"+Class_id).empty();
$("#"+Class_id).append( renderedPage );
in one line
$("#"+Class_id).empty().append( renderedPage );
If I understood correctly, you want to use dynamic selector based on passed parameter. You can do something like:
function doSomething(className) {
var selector = "#" + className; // # for id, . for class
$(selector).empty();
$(selector).append(something);
}
Optimized version would be:
function doSomething(className) {
var x = $("#" + className); // # for id, . for class
x.empty();
x.append(something);
}
Optimized = you look for the element in DOM only once
Try this in order to select class use dot .
$("#"+Class_id).empty();
$("#"+Class_id).append( renderedPage );

Use jquery to change the class of a target element from array

I have a List li of elements that I used .toArray(). I now need to loop through them to find the desired element and change its style Class.
I am not sure what I am doing wrong, but I cannot seem to get the class of the index item, but I can retrieve the innerHTML no problem.
var viewsIndex = $('#viewsList li').toArray()
for(i=0; i < viewsIndex.length; i++) {
if(viewsIndex[i].innerHTML == selectedTab) {
console.log(viewsIndex[i].attr('style')); //This does NOT work
console.log(viewsIndex[i].innerHTML); //This does work
}
else
{
}
}
Once I target the Element, I want to use .removeClass and .addClass to change the style.
This is the DOM object which doesn't have jQuery functions:
viewsIndex[i]
This is the jQuery object which has the attr function:
$(viewsIndex[i]).attr('style')
Anyway, your code could be a lot simpler with this:
$('#viewsList li').filter(function(){
return this.innerHTML == selectedTab;
}).removeClass('foo').addClass('bar');
You are trying to call jQuery function on DOM object convert it to jQuery object first.
Change
viewsIndex[i].attr('style')
To
$(viewsIndex[i]).attr('style')
couldn't you use .each()?
$('#viewLists li').each(function(i){
if($(this).html == selectedTab){
$(this).removeClass('foo').addClass('bar');
}
});
Loop over the elements using jQuery each and then access them as $(this). This way you'll have access to jQuery methods on each item.
$('#viewsList li').each(function(){
var element = $(this);
if(element.html() == selectedTab){
console.log(element.attr('style')
} else {
}
}

jquery reset after()

is there a way to reset/update an after() element? Not add another after() text. Thank you
Maybe this will helpful.
(Controller function for Emptiness of Form to be sent Server Input parameter ID of Form Parent DIV, output is 1-true, 0 false)
function emptynessCntrl(elementosForControl){
var controlResult=1;
$(elementosForControl).find('input').each(function() {
if($(this).val().trim()===""){
controlResult=0;
console.log($(this).attr('id')+' Element is empty');
$(this).nextAll().remove();
$(this).after('<div class="err-label">'+$(this).attr('placeholder')+' is empty</div>');
return controlResult;
}
else{
$(this).nextAll().remove();
}
});
return controlResult;
}
Your question is not clear. I'll asume you want to modify an element added with .after()
Instead of doing this:
$("#elem1").after('<div id="after />");
You could do this (use insertAfter)
$('<div id="after" />').insertAfter("#elem1").attr("width", 200).html("hi") ...;
Hope this helps.
Cheers.
When you add the element, give it a name
var newElement = $('<span>Some new stuff</span>');
$('.whatever').after(newElement);
Then, when you want to change it, simply remove the previous one first
newElement.remove();
newElement = $('<div>And now for something completely different</div>');
$('.whatever').after(newElement);
You can write a function that uses .data() to remember the new element as such: (I would change the names a bit though)
$.fn.addUniqueSomething = function (content) {
var existing = this.data('something-that-was-already-added');
if (existing) {
existing.remove();
}
var something = $(content);
this.after(something);
this.data('something-that-was-already-added', something);
};
Then you can use
$('.whatever').addUniqueSomething('<span>Some new stuff</span>');
// and later...
$('.whatever').addUniqueSomething('<div>And now for something completely different</div>');
And the second one will replace the first

Categories