Jquery hasClass issue - javascript

im trying to check if one of the DIV's has class "visible" which is being add by a jquery plugin, it seems not to work.
it works when i check the first element, but if i want to check next div, it doenst finds it.
help is appreciated.
My DIV
<div class="swiper-slide welcome" id="welcome"></div>
2nd DIV
<div class="swiper-slide intro-early-life" id="intro-early-life"></div>
MY JQUERY
<script type="text/javascript">
$(document).ready(function() {
if ($('.welcome').hasClass('swiper-slide-visible')) {
alert("working");
}
});
</script>
Im not using same ID, maybe it was my bad explanation. I can use the class as well, no difference.

$(document).ready(function() {
if ($('#welcome').hasClass('swiper-slide') && $('#welcome').hasClass('visible')) {
alert("working");
}
});

if ($('#welcome').is(":visible") && $('#welcome').hasClass("swiper-slide")) {
alert("Yeah!");
}
Perhaps that would work better?
Edit: Also swiper-slide-visible class doesn't exist on the page - perhaps this is the issue...?

You can use also as
$(document).ready(function() {
if ($('#welcome').hasClasses(['swiper-slide', 'visible']);) {
alert("working");
}
});
$.fn.extend({
hasClasses: function (selectors) {
var self = this;
for (var i in selectors) {
if ($(self).hasClass(selectors[i]))
return true;
}
return false;
}
});

Use .is()
if ($('#welcome').is('.swiper-slide, .visible'){
Id Must Be unique you can use classes instaed
Two HTML elements with same id attribute: How bad is it really?

You could use .is() instead:
$(document).ready(function() {
if ($('.welcome').is('.swiper-slide.visible')) {
alert("working");
}
});

Related

Run jQuery function only if CSS class is present

I made a simple jQuery function that trims text. I trigger it this way:
// JS
function truncate() {
<! – Stuff to do -->
}
truncate();
// ...
// HTML
<div class="Truncate" data-words="60">
<! – Text to Trim -->
</div>
The problem is that the function gives me an error every time I load a page that doesn't have a DIV with the class 'Truncate' on it.
So I'd like to trigger it only when that <div> is there.
Actually I'd like that the <div> itself triggers the function.
I know I can wrap it in an IF statement checking for the class, but I was wondering if with jQuery I can call it over a selector, something like:
$('.Truncate').myfunctionName() {
my stuff
};
That is creative syntax, just to make you understand.
...Thanks in advance.
Simple answer If I got it right.
function doStuff(elements) {
console.log('doing stuff...');
}
$(function() {
var truncates = $('.Truncate');
if (truncates.length) { // here you validate if there is any element with that class
doStuff(truncates);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Truncate"></div>
Here is a js code with an IFEE function:
(function(){
var elmTranc=document.getElementsByClassName('Truncate');
if(elmTranc){
for(var i=0;i<elmTranc.length;i++){
elmTranc[i].innerHTML.trim();
}
}
})();
Another simple solution using querySelector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
if(document.querySelector(".Truncate")){ //if element with .Truncate exists
truncate();
}
You can create a mini jquery plugin:
// include jquery first
$.fn.truncate = function() {
return $(this).each(function() {
$(this).text($(this).text().substr(0, 2));
});
};
$(".truncate").truncate()
$(".someotherclass").truncate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='truncate'>Abc</div>
<div class='truncate'>Xyz</div>
<div class='notruncate'>123</div>
I've done this in the end...
if( $('.Truncate').length ) {
(function() {
suff
})();
}
Is it ok?

Change an ID upon click

I know how to change a class name with another class upon click, but not sure how to do so when using id instead.
Below is how the class is setup:
<script>
$(function(){
$(".collapseArrow").click(function(){
$(".collapseArrow").removeClass("collapseArrow")
$(this).addClass("collapseArrowUp")
return false;
})
})
</script>
The reason for that is that the class is already being used and i have to use the id to style it instead.
Plain Javascript approach:-
This approach takes advantage of the this keyword as follows...
HTML:
<div id="oldId" onclick="changeId(this)"></div>
JS:
function changeId(element) {
element.id = "someNewId";
}
or simply (in one line) as part of the HTML
<div id="oldId" onclick="this.id='someNewId';"></div>
jQuery approach:-
Use the attr() function as follows...
$(function(){
$("#oldId").click(function(){
$("#oldId").attr("id","newId");
return false;
});
});
EDIT: As requested, I will give a piece of code to toggle between 2 ids.
HTML:
<div id="firstId" onclick="toggleId(this)"></div>
JS:
function toggleId(element) {
if(element.id == "firstId") {
element.id = "secondId";
} else { //This will only execute when element.id == "secondId"
element.id = "firstId";
}
}
You can use the attr() function
<script>
$(function(){
$("#collapseArrow").click(function(){
$("#collapseArrow").attr('id',"collapseArrowUp");
return false;
});
});
</script>
Instead of changing the id, do it with multiple classes.
This could help you...
$(function(){
$(".collapseArrow").click(function(){
$(".collapseArrow").removeClass("up")
$(this).addClass("up")
return false;
})
})
You can use
$(this).attr("id"',"new id");
But i would use classes and add important to override existing css rules
Hope i helped
i have to use the id to style it instead.
I suggest you not to do this because in the dom structure ids have most preference against the class names. So this would be little difficult to override the styles which have been applied with the ids.
Instead i would recommend to use classes instead:
$(function() {
$(".collapseArrow").click(function() {
$(this).toggleClass("collapseArrow collapseArrowUp")
return false;
});
});
$(function() {
$(".collapseArrow").click(function() {
$(this).toggleClass("collapseArrow collapseArrowUp")
return false;
});
});
.collapseArrow::before {
content: "[-]"
}
.collapseArrowUp::before{
content: "[+]"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class='collapseArrow'></h1>
You should not change an id. If you need to use a different selector to select the same element, add another class to the element, e.g.
<span class="collapsArrow SomethingMeaningful"></span>
Then you just need to use a different selector method:
$( "span[class~='SomethingMeaningful']" )
.removeClass("collapseArrow")
.addClass("collapseArrowUp");
Then you can style the element with:
.SomethingMeaningful{
}

If div is empty, remove it and change class of next div

Some generated output can be as follows:
<div class="fivecol"></div>
<div class="sevencol">content</div>
if the div.fivecol is empty, I want to remove it and change the div.sevencol to a div.twelvecol
$('.fivecol').each(function() {
if ($(this).html() ==''){
$(this).remove().next('sevencol').removeClass('sevencol').addClass('twelvecol');
}
});
doesn't do the trick. Any ideas?
$('.fivecol:empty + .sevencol').toggleClass('sevencol twelvecol')
.prev()
.remove();
DEMO: http://jsfiddle.net/JY9NN/
$('.fivecol').each(function(i, div) {
if (!div.html().trim()) {
div.remove().next('sevencol').removeClass('sevencol').addClass('twelvecol');
}
});
basically I just fixed some syntax errors, and changed the this reference to the proper argument call. Let me know how that works.
Best,
-Brian
Try this,
$(function () {
$('.fivecol').each(function() {
if ($(this).html() =='') {
$(this).remove();
$('.sevencol').each(function(){
$(this).attr('class','twelvecol');
});
}
});
});
We could use a couple fancy selector tricks:
$(".fivecol:empty + .sevencol").attr("class", function(){
return $(this).prev().remove(), "twelvecol";
});
As you can probably guess, .fivecol:empty attempts to find an empty element with the class fivecol. It then proceeds to grab the sibling element, using +, which has the class .sevencol.
Once we have our .sevencol element, we set out to change its class value to twelvecol. Since we're in this function, we know that .fivecol:empty was found, so we can safely remove it. Lastly, we simply return the new class value to be assigned in the place of sevencol.
Demo: http://jsfiddle.net/cLcVh/1/

JQuery with Element ID

I am trying to create a bit of jquery code to update an element but im having a problem. It wont update and I think its because of the element id?
Here is my JS Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#vote_button_" + $(this).attr('id')).click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
And this is the HTML Code:
<div class="vote_container">
<div class="vote_button" id="vote_button_31"><img src="/images/picture_31.png"></div>
<div class="vote_count" id="vote_count">0</div>
</div>
You're telling it to use the ID of the document (I think).
You can surely just do:
$("#vote_button_31").click(function()
{
$("#vote_count").show().html('<h2>voting, please wait...</h2>');
});
If you want the code to work on all vote buttons try this:
$(".vote_button").click(function()
{
$(this).siblings('.vote_count').show().html('<h2>voting, please wait...</h2>');
});
$("#vote_button_" + $(this).attr('id')).click(function()...
The way you've called it, this has no context at all. Since you have a class on the div in question, why not use that instead?
$(".vote_button").click(function() {...
That will also work if you don't know the id in question when the page is loaded. If you're dynamically adding the divs then you might want to use live or delegate:
$(".vote_button").live("click", function() {...
Why you don't select the element directly:
<script type="text/javascript">
$(document).ready(function()
{
$("div#vote_button_31").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
YOu cannot do this. Instead try this:
<script type="text/javascript">
$(document).ready(function()
{
$(".vote_button").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});

Live query plugin doesn't work with the visible attribute selector

I have the following running in the jquery ready function
$('[id$=txtCustomer]:visible').livequery(
function() { alert('Hello') },
function() { alert('World') }
);
I get an alert for the first time saying 'Hello' but the functions are not called onwards when i toggle this visibility of the textbox.
Please help.
The livequery "match/nomatch" events don't work with jQuery pseudoselectors like ":visible". They do work for class selectors.
An easy fix would be to also add a class when you show the item, and remove a class when you hide the item.
For example:
(html)
<input type="button" value="toggle"/>
<div id="item"
style="width:100px;height:100px;background-color:#ff0"
class="Visible">
</div>
(script)
$(function() {
$("#item.Visible").livequery(
function() {
alert("match");
},
function() {
alert("nomatch");
}
);
$("input").click(function() {
if ($("#item").is(":visible"))
$("#item").hide().removeClass("Visible");
else
$("#item").show().addClass("Visible");
});
});
A demonstration of this can be found here: http://jsbin.com/uremo

Categories