Add a limit to the class selector "dog" - javascript

I want this code to change the class of 3 divs maximum using jQuery.
$(".cat, .dog").click(function() {
var el = $(this);
if(el.hasClass('cat')) {
el.removeClass('cat');
el.addClass('dog');
} else {
el.removeClass('dog');
el.addClass('cat');
}
});
// I tried with this code but it does not work, since I can keep dialing more than 3
$(document).ready(function () {
$(".cat").change(function () {
var maxAllowed = 3;
var cnt = $(".dog").length;
if (cnt > maxAllowed) {
addClass('cat');
}
});
});
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>

To achieve that, you have to add one more check: the amount of elements with class dog should be less than maxAllowed value. The condition should look something like that:
el.hasClass('cat') && activeDogs < maxAllowed // activeDogs - the amount of elements with class "dog"
And finally you will get something close to that:
var maxAllowed = 3;
$(".cat, .dog").click(function() {
var el = $(this);
var activeDogs = $('.dog').length;
if (el.hasClass('cat') && activeDogs < maxAllowed) {
el.removeClass('cat');
el.addClass('dog');
} else {
el.removeClass('dog');
el.addClass('cat');
}
});
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>
I get $('.dog').length every time, because I guess, that classes can be added/removed not only through this function. But if so, you can simply use a counter to achieve that and compare the counter with maxAllowed variable, this operation will take less resources.
var maxAllowed = 3;
var activeDogs = 0;
$(".cat, .dog").click(function() {
var el = $(this);
if (el.hasClass('cat') && activeDogs < maxAllowed) {
el.removeClass('cat');
el.addClass('dog');
activeDogs++;
} else if (el.hasClass('dog')) {
el.removeClass('dog');
el.addClass('cat');
activeDogs--;
}
});
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>

Try to increment the count after you add the cat class:
$(document).ready(function () {
var count = 0;
$(".cat").change(function () {
if (count < 3) {
addClass('cat');
count++;
}
});
});

You can just check if you have less than 3 "dogs" (red colored rows) before allowing the class change:
$(".cat, .dog").click(function() {
var el = $(this);
if(el.hasClass('cat') && $('.dog').length < 3) {
el.removeClass('cat');
el.addClass('dog');
} else {
el.removeClass('dog');
el.addClass('cat');
}
});
// I tried with this code but it does not work, since I can keep dialing more than 3
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>

Related

swap div's position from top div's

I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML
<div class="wrap top">
<input type="text" value="div1" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div3" class="textbox " />
</div>
jQuery
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(this).insertBefore($(this).prev());
}
});
}(jQuery));
The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?
I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(".wrap").removeClass("top");
$(this).addClass("top");
}
});
}(jQuery));
this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
var $this = $(this);
if ($this.index() == 0) {
} else {
var first = $this.siblings('.wrap').first();
first.insertBefore($this);
$this.prependTo($this.parent());
}
});
if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());
To swap the two DOM elements using jQuery, you could use something like this: -
(function($) {
$(".wrap").on("click", function(event) {
var index = $(event.target).index();
var first = $(".wrap").first();
if (index > 0) {
$(first).swapWith(this);
}
});
}(jQuery));
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
.wrap {
height: 100px;
width: 200px;
margin: 10px 10px 10px 10px;
background-color: #2d8cd0;
}
h2 {
color: white;
text-align: center;
padding-top: 20px;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrap">
<h2>1</h2>
</div>
<div class="wrap">
<h2>2</h2>
</div>
<div class="wrap">
<h2>3</h2>
</div>
<div class="wrap">
<h2>4</h2>
</div>

Jquery hide first 12 elementes, show next 12 elements

what i am trying to do is make the first 12 elements hidden and show the next 12 elements.
//this is dynamic loaded content
<div class="inner-content">
<div class="front-pro">1</div>
<div class="front-pro">2</div>
<div class="front-pro">3</div>
<div class="front-pro">4</div>
<div class="front-pro">5</div>
<div class="front-pro">6</div>
<div class="front-pro">7</div>
<div class="front-pro">8</div>
<div class="front-pro">9</div>
<div class="front-pro">10</div>
<div class="front-pro">11</div>
<div class="front-pro">12</div>
<div class="front-pro hidden">13</div>
<div class="front-pro hidden">14</div>
..... etc (200 divs more)
</div>
<div onclick="SearchNext();">next</div>
This is my javascript/jquery:
function SearchNext(){
var first = $('.inner-content').children('.front-pro:hidden:first');
first.prevAll(':lt(12)').hide();
first.nextAll(':lt(12)').show();
}
It works one time, after it stops working. (and it skips number 13)
i want to have 12 new elements visible with each Next click and hide the previous.
UPDATE - this is my end result that works perfectly
JSFIDDLE DEMO
Thanks to Alex Char
PHP for creating page numbers, you could do this also with javascript
//$counter is search results
$x = 1;
$Pnumbers = '';
while($x <= ceil($counter/12)) {
if($x == 1){ $ecl = 'bold'; } else{ $ecl = ''; }
$Pnumbers .= ' <span class="number '.$ecl.' numbering" onClick="GoTo('.$x.');">'.$x.'</span> ';
$x++;
}
if($counter > 12){ echo'<div class="page-numbers">
<span class="prev number" onclick="GoTo(\'prev\')">Prev</span>
'.$Pnumbers.'
<span class="next number" onclick="GoTo(\'next\');">Next</span>
</div>'; }
Javascript:
function GoTo(nn) {
var nng = parseInt($('.page-numbers .numbering.bold').text());
if(nn == 'next'){
nn = nng+1;
}if(nn == 'prev'){
nn = nng-1;
}
//get all child elements with class front-pro
//of element with class .inner-content
var childElems = $(".inner-content .front-pro");
var totalpages = Math.ceil(childElems.length/12);
//iterate through the elements
var first = (nn-1)*12;
var last = first+11;
childElems.each(function(i, el) {
//show the elements that match the criteria removing css class
if (i >= first && i <= last) {
$(el).removeClass('hidden');
} else {
//hide rest
$(el).addClass('hidden');
}
});
if(nn > 1){ $('.page-numbers .prev').show(); }else{ $('.page-numbers .prev').hide(); }
if(nn < totalpages){ $('.page-numbers .next').show(); }else{ $('.page-numbers .next').hide(); }
$('.page-numbers .numbering').removeClass('bold');
$('.page-numbers .numbering:eq('+(nn-1)+')').addClass('bold');
}
CSS:
.front-pro.hidden{ display:none !important; }
.prev { display: none; }
.page-numbers .number{
background: #ff0000; }
.page-numbers{ text-align:center; }
.page-numbers .number.bold{ font-weight:bold; background:#000; }
.page-numbers .number:hover{ background:#000; cursor: pointer; }
Make sure that the first 12 divs do not contain the "hidden" class, all the divs that come after should have "hidden" in there class
I change a bit the implementation to support and previous. I use a css class to hide content.
function searchNext() {
$('.inner-content').children('.front-pro:lt(12)').addClass('hidden');
$('.inner-content').children('.front-pro:gt(11)').removeClass('hidden');
$(".next").hide();
$(".prev").show();
}
function searchPrev() {
$('.inner-content').children('.front-pro:lt(12)').removeClass('hidden');
$('.inner-content').children('.front-pro:gt(11)').addClass('hidden');
$(".next").show();
$(".prev").hide();
}
.front-pro.hidden {
display: none;
}
.prev {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner-content">
<div class="front-pro">1</div>
<div class="front-pro">2</div>
<div class="front-pro">3</div>
<div class="front-pro">4</div>
<div class="front-pro">5</div>
<div class="front-pro">6</div>
<div class="front-pro">7</div>
<div class="front-pro">8</div>
<div class="front-pro">9</div>
<div class="front-pro">10</div>
<div class="front-pro">11</div>
<div class="front-pro">12</div>
<div class="front-pro hidden">13</div>
<div class="front-pro hidden">14</div>
</div>
<div class="next" onclick="searchNext();">next</div>
<div class="prev" onclick="searchPrev();">prev</div>
I create a general solution after your comment with next and previous(I use step 3 for demo purposes but you can use what ever you want):
var pager = (function() {
/*declare private variables*/
var first = 0,
last = 2,
step = 3;
function searchNext() {
//next function
//increasing first and last variables
first += step;
last += step;
pagerHelper();
}
function searchPrev() {
//previous function
//decrease first and last variables
first -= step;
last -= step;
pagerHelper();
}
function pagerHelper() {
//get all child elements with class front-pro
//of element with class .inner-content
var childElems = $(".inner-content .front-pro");
//iterate through the elements
childElems.each(function(i, el) {
//show the elements that match the criteria removing css class
if (i >= first && i <= last) {
$(el).removeClass('hidden');
} else {
//hide rest
$(el).addClass('hidden');
}
});
nextPreviousToggle(childElems.length);
}
function nextPreviousToggle(maxEle) {
//here the code is to show/hide next/previous buttons
if (last >= maxEle) {
$(".next").hide();
} else {
$(".next").show();
}
if (first === 0) {
$(".prev").hide();
} else {
$(".prev").show();
}
}
return {
searchNext: searchNext,
searchPrev: searchPrev
}
})();
.front-pro.hidden {
display: none;
}
.prev {
display: none;
}
.prev:hover,
.next:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner-content">
<div class="front-pro">1</div>
<div class="front-pro">2</div>
<div class="front-pro">3</div>
<div class="front-pro hidden">4</div>
<div class="front-pro hidden">5</div>
<div class="front-pro hidden">6</div>
<div class="front-pro hidden">7</div>
<div class="front-pro hidden">8</div>
<div class="front-pro hidden">9</div>
<div class="front-pro hidden">10</div>
<div class="front-pro hidden">11</div>
<div class="front-pro hidden">12</div>
<div class="front-pro hidden">13</div>
<div class="front-pro hidden">14</div>
</div>
<span class="next" onclick="pager.searchNext();">next</span>
<span class="prev" onclick="pager.searchPrev();">prev</span>
References
:gt()
:lt()
You use the following code to handle any number of divs,
var x = $(".inner-content div").hide();
$("div:contains(next)").click(function() {
var cnt = $(this).data("cnt") || 0;
if((cnt * 12) > x.length){ cnt = 0; }
x.hide().filter(":eq("+ (cnt * 12) + "), :lt(" + ((cnt * 12) + 12) + "):gt(" + (cnt * 12) + ")").show();
$(this).data("cnt", ++cnt);
});
DEMO
Try this instead
$('.inner-content').children().each(function (i, x) {
if (i < 12) // Hide First 12 i.e 0-11
$(x).addClass('hidden');
else if (i < 24) // Show Next 12 i.e 12-23
$(x).removeClass('hidden');
})
Also make sure you have css rule defined as
.hidden {
display: none;
}

How to count dynamically div display block?

I have 3 div. 2 are hidden by default.
By clicking on a link "add" or a link "remove", I want the other div to be shown or hidden. And then, I would like to count dynamically div which are shown.
Here is my HTML :
<div id="clone1" class="billet">
<input type="text" /><span id="test"></span>
</div>
<div id="clone2" class="billet" >
<input type="text" />
</div>
<div id="clone3" class="billet" >
<input type="text" />
</div>
<div id="ajout-suppr">
<a href="javascript:;" class="ajoutBillet" >Ajouter un billet</a>
<span>-------------</span>
<a href="javascript:;" class="supprBillet" >Supprimer un billet</a>
</div>
jQuery :
$(document).ready(function () {
$(".supprBillet").hide();
$("#clone2").hide();
$("#clone3").hide();
$(".ajoutBillet").click(function (){
var nb = $('.billet:not([style*="display: none"])').size();
$('#test').html(nb);
if(nb < 2) {
$(".supprBillet").hide();
}
else {
$(".supprBillet").show("slow");
}
if($("#clone2").hide()) {
$("#clone2").show("slow");
}
if($("#clone3").hide() && $("#clone2").show()) {
$("#clone3").show();
}
if($("#clone3").show() && $("#clone2").show()) {
$(".ajoutBillet").hide("slow");
}
}); // fin du click function ajout billet
$(".supprBillet").click(function (){
var nb = $('.billet:not([style*="display: none"])').size();
if(nb < 2) {
$(".supprBillet").hide();
}
else {
$(".supprBillet").show();
}
if($("#clone2").show() && $("#clone3").hide()) {
$("#clone2").hide();
}
}); // fin du click function suppr billet
});
As you see nothing works.
Could you please show me an issue?
Thanks in advance.
you can try something like this:
jQuery('.ajoutBillet').on('click',function(){
var lengthDivs = jQuery('.billet:visible').length;
if(lengthDivs < 2 && jQuery('.supprBillet:visible').length > 0){
jQuery('.supprBillet').hide();
}
});
I made this into a fiddle. This does seem to do what is expected (by code). Are you referencing the jquery library?
I did make some changes to your count by checking on 1
if(nb < 1) {
$(".supprBillet").hide();
}
You need to check the visible div by jquery .is(':visible') function.
Like this way :
Replace this
var nb = $('.billet:not([style*="display: none"])').size();
With
var nb = $('.billet').is(":visible").length;
Now shows and hides the inputs:
$(document).ready(function() {
$(".billet input:nth-child(1)").hide();
$(".billet input:nth-child(2)").hide();
$("#new").click(function() {
var count = 0;
$(".billet input").each(function() {
if ($(this).is(":visible")) {
count++;
}
});
$(".billet input:nth-child("+count+")").show();
if ($("#total-divs").html() < 3) {
$("#total-divs").html(count+1);
}
});
$("#delete").click(function() {
var count = -1;
$(".billet input").each(function() {
if ($(this).is(":visible")) {
count++;
}
});
if (count > 0) {
$(".billet input:nth-child("+count+")").hide();
$("#total-divs").html(count);
}
});
});
input {
margin: 4px 0;
width: 100%;
}
.actions {
display: block;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="billet" >
<input type="text" />
<input type="text" />
<input type="text" />
</div>
<div class="actions">
New | Delete
</div>
Total: <span id="total-divs">1</span>

Select concrete DOM element without ID

When I'm typing a login or password, tooltip appears with one or more sentences.
Every tooltip has the same z-index, but I want to change it to higher when I'm focused at adequate input and bring it back at blur event, but I might have 10 inputs with many options in tooltip. Is it possible to write function without using ID of tooltip?
$(document).ready(function() {
$('input').focus(function() {
$('div.tooltip').addClass("active");
});
$('input').blur(function() {
$('div.tooltip').removeClass("active");
});
$('#login').keyup(function() {
var th = document.getElementById('login').value;
if (th.length < 6) {
$('#result').css('display', 'inline');
var ex = $("#too_short").text();
if (!ex) {
$('#result').append('<p id="too_short">Too short password.</p>');
}
} else {
$("#too_short").remove();
}
if (th.contains('\'') || th.contains('\"') || th.contains('\\') || th.contains('\/')) {
$('#result').css('display', 'inline');
var en = $("#forb_char").text();
if (!en) {
$('#result').append('<p id="forb_char">Forbidden characters</p>');
}
} else {
$("#forb_char").remove();
}
});
$('#pwd').keyup(function() {
var th = document.getElementById('pwd').value;
if (th.length < 6) {
$('#result1').css('display', 'inline');
var ex = $("#too_short1").text();
if (!ex) {
$('#result1').append('<p id="too_short1">Too short password.</p>');
}
} else {
$("#too_short1").remove();
}
if (th.contains('\'') || th.contains('\"') || th.contains('\\') || th.contains('\/')) {
$('#result1').css('display', 'inline');
var en = $("#forb_char1").text();
if (!en) {
$('#result1').append('<p id="forb_char1">Forbidden characters</p>');
}
} else {
$("#forb_char1").remove();
}
});
});
.tooltip {
position: absolute;
border: 2px solid red;
display: none;
margin-left: 250px;
background: blue;
z-index: 1;
color: white;
}
.active
}
z-index:999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form name="form" id="form" method="post">
<div id="result" class="tooltip"></div>
<span> Write login: </span>
<input id="login" name="login" type="text" />
<br/>
<div id="result1" class="tooltip"></div>
<span> Write pwd: </span>
<input id="pwd" name="pwd" type="text" />
</form>
<!-- How to addClass active to proper div.tooltip? -->
Something like this? :
http://jsfiddle.net/9n2db67u/22/
Your code is very messy. Try to use TidyUp when posting jsfiddle links..
$('input').on('click', function () {
$('.active').removeClass('active');
$(this).prevAll('div').addClass('active'); //.css('z-index', '20000');
});

Calling function from anonymous function in JQuery returns undefined

I'm working with this script which needs to call the external function, but the value returned in the log shows 'undefined'.
I have a checkbox that calls the external function successfully, but the anonymous jQuery function is not successful. Could this be a scope issue of some sort?
Thanks for any help.
css:
div.row {
border: 1px solid blue;
width: 100px;
}
div.child {
border: 1px solid red;
display: inline-block;
}
javascript:
function padZeros(ksa) {
getDigits(ksa);
//alert(s);
//document.getElementById("ksa_padded").value=s
}
function getDigits(MyDigits) {
var ksa = MyDigits;
var re4Digit = /^([0-9])([0-9]?)([k|s|a])([0-9])([0-9]?)([A-z]?)$/;
var first2Digits = ksa.replace(re4Digit, "$1$2");
//alert(first2Digits);
//return first2Digits;
pad(first2Digits, '2');
}
function pad(num, size) {
//var s = num+"";
//alert(num);
s = num + "";
//alert(s);
while (s.length < size) s = "0" + s;
return s;
//alert(s);
}
$("#add").click(function () {
var inserted = false;
var newText = $("#addText").val();
var $newItem = $("<div class='child'>" + newText + "</div>");
$(".row:first .child").each(function () {
//alert($(this).text());
xx = $(this).text();
var compare_a = padZeros(xx);
//alert(compare_a);
console.log(xx);
if ($(this).text() > newText) {
$newItem.insertBefore($(this));
inserted = true;
return false;
}
});
if (inserted == false) {
$newItem.appendTo(".row:first");
}
});
html
<div class="row">
<div class="child">3K1</div>
<div class="child">3K3</div>
<div class="child">3K4</div>
<div class="child">1K1</div>
<div class="child">1K2</div>
</div>
<div class="row">
<div class="child">IS2</div>
<div class="child">IS4</div>
</div>
<div class="row">
<div class="child">IA2</div>
<div class="child">IA4</div>
</div>
<br/>
<input id="addText" type="text" />
<input id="add" type="button" value="Insert Element" />
<br>
<input type="checkbox" onClick="padZeros('1k10s')">
<input type="text" id="ksa_padded">
Try
return getDigits(ksa);
return pad(first2Digits,'2');
You have to return things, otherwise they'll come out as undefined.

Categories

Resources