Adding a integer to a css class with jQuery - javascript

This is the code I have, now what it needs to do is increase the integer after the class name 'icon-' so that on each click the 'icon-' class gets a higher integer value ex. click -> 'icon-2', click -> 'icon-3' and so forth.
Bare in mind that the current icon shown to the user is 'icon-1'.
Also, is there a way for me to alert if it hits 'icon-10' or prevent it from trying to go further than 'icon-10' or below 'icon-1'.
$(function () {
a = 2,
b = '',
$('.icon-step-backward').click(function(){
$('#slider').removeClass();
$('#slider').addClass('icon-' - a);
});
$('.icon-step-forward').click(function(){
$('#slider').removeClass('icon-');
$('#slider').addClass('icon-' + a);
});
});

$('.icon-step-backward, .icon-step-forward').click(function () {
var s = $(this).hasClass('icon-step-backward') ? -1 : 1;
$('#slider').prop('className', function (_, p) {
return p.replace(/\d+/g, function (n) {
var j = +n + s;
return j <= 10 && j >= 1 ? j : n;
});
});
});
http://jsfiddle.net/Mwcbp/

$(function () {
var classes=["icon-1","icon-2","icon-3","icon-4","icon-5","icon-6"
,"icon-7","icon-8","icon-9","icon-10"];
var classCounter=0;
$('.icon-step-backward, .icon-step-forward').click(function () {
//caching slider object
var $slider = $('#slider'),
s = $(this).hasClass('icon-step-backward') ? -1 : 1,
tmp=counter+s,
disableButton=(s==-1)?'.icon-step-backward':'.icon-step-forward',
enableButton=(s==-1)?'.icon-step-forward':'.icon-step-backward';
$(enableButton).show();
if(tmp<classes.length && tmp>0){
$slider.removeClass(classes[counter]);
counter=counter+s;
$slider.addClass(classes[counter]);
}else{
$(disableButton).hide();
}
});
});
If you have multiple .icon-step buttons having to manipulate multiple slider (#slider suggest otherwise) than you can add the classCounter as $("#slider").data to be used specifically for this slider.

Related

List item fade when navigating

I have a group of list items that I control through "Next" and "Prev" buttons. The code shows five list items at a time, if there are more you can click "Next" and you'll see another five - if you click "Prev" you'll see the previous five...pretty simple operation and it works. You can see a live example at: http://joshrodg.com/hallmark/events/.
The javascript I am using is:
$(document).ready(function () {
var $li = $('.eo-events li');
$li.hide().filter(':lt(5)').show()
var x = 5;
$('#next, #prev').click(function () {
var m = this.id === 'prev' ? 'first' : 'last';
var $m = $li.filter(':visible')[m]()[this.id + 'All'](":lt(" + x + ")");
if ( $m.length == 0 ) return;
$li.hide();
$m.show();
});
});
http://jsfiddle.net/479Fr/
What I'd like to do is have the items fade-in instead of just appearing...kind of like: https://codepo8.github.io/simple-carousel/carousel-pointer-events.html (or something similar)
I know there are some carousels out there that can do this, but I don't need something that bulky, especially since the functionality already works with such a small amount of code.
Is there a simple modification I can make to what I'm already using to accomplish something like this?
Thanks,
Josh
Use the JQuery .fadein/out to have fading animations
http://api.jquery.com/fadein/
Like that :
$(document).ready(function () {
var $li = $('#myList li');
$li.hide().filter(':lt(5)').show()
var x = 5;
$('#next, #prev').click(function () {
var m = this.id === 'prev' ? 'first' : 'last';
var $m = $li.filter(':visible')[m]()[this.id + 'All'](":lt(" + x + ")");
if ( $m.length == 0 ) return;
var time = 250;
$li.fadeOut(time);
setTimeout( function(){
$m.fadeIn(time);
}, time);
});
});

jQuery autocomplete strange behavior

I've got an issue with jQuery's autocomplete. What I am trying to do is show a suggestions list based on input. So, for instance, on input class="font" I want to have a list of font sizes and on input class="color" to have a list of color predictions.
Here is what I have:
function suggestions(input, element) {
var suggestions = [];
if (element.hasClass("color") !== -1) {
var i = 0;
while (i < 100) {
suggestions.push("color" + i.toString()); // for testing purpose
i++;
}
} else {
var nr = 1;
while (nr < 1025) {
suggestions.push(nr.toString() + "px");
nr = nr + 1;
}
}
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
var counter = 0;
var filteredArray = $.map(suggestions, function (item) {
if (item.startsWith(request.term) && counter < 10) {
counter = counter + 1;
return item;
} else {
return null;
}
});
response(filteredArray);
},
autoFocus: true
});
}
The thing is, it works perfectly when I test it for inputs having any class except 'color'. When it detects a class with 'color', it will build the suggestions array accordingly but will refuse to get into the anonymous function inside autocomplete - source. Which is odd to me, 'cause the array is always constructed and the autocomplete should always be hit.
Any ideas?
Thanks!
jQuery's .hasClass() returns boolean value, so you code should look like:
if (element.hasClass("color")) { ... }
Try this JSFiddle (type symbol "c")

How to increase and decrease a counter from one button - click and click again jQuery

This is the code that I am currently using:
<script>
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1+1 });
});
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1-1 });
});
</script>
When the user clicks on the button, the value of #lke increases by 1. When he clicks again, the value decreases by 1. The code that I am currently using does not work so how would I fix this?
You can use an external var to decide if you have to increment o decrement the value
<script>
var increment = true;
$(".lk").click(function(){
var lke = $(this).find("#lke"),
value = parseInt(lke.html()) || 0;
lke.html( increment ? value + 1 : value - 1);
increment = !increment;
});
</script>
Your code doesn't work because you assign two events for every click - one which increases the value and one which decreases it, so nothing happens.
You could use an external variable such as toAdd to determine which action to do:
var toAdd = 1;
$(".lk").click(function(){
newValue = oldValue + toAdd;
toAdd *= -1;
...
});
You put two call of the same object, try this instead
<script>
var val = 0; // Put the original value
var negative = false;
$( document ).ready(function() { // You need to declare document ready
$(".lk").click(function(){
val = val + ((negative) ? -1 : 1); // Change if its positive or negative
negative = (negative) ? false : true;
$("#lke").text(val); // Adjust the html ?
});
});
</script>
Try something like this:
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).removeClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).addClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});
You could also use a data attribute instead of checking for a class aswell.
Or use toggleClass().
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).toggleClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).toggleClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});

jQuery "keyup" crashing page when checking 'Word Count'

I have a word counter running on a DIV and after typing in a few words, the page crashes. The browser continues to work (par scrolling) and no errors are showing in Chrome's console. Not sure where I'm going wrong...
It all started when I passed "wordCount(q);" in "keyup". I only passed it there as it would split-out "NaN" instead of a number to countdown from.
JS:
wordCount();
$('#group_3_1').click(function(){
var spliced = 200;
wordCount(spliced);
}) ;
$('#group_3_2').click(function(){
var spliced = 600;
wordCount(spliced);
}) ;
function wordCount(q) {
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0)
var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
$('.message1').keyup(function() {
wordCount(q);
});
try
{
if (new Number( word_count ) < 0) {
$(".word_count").attr("id","bad");
}
else {
$(".word_count").attr("id","good");
}
} catch (error)
{
//
}
};
HTML:
<input type="checkbox" name="entry.3.group" value="1/6" class="size1" id="group_3_1">
<input type="checkbox" name="entry.3.group" value="1/4" class="size1" id="group_3_2">
<div id="entry.8.single" class="message1" style="height: 400px; overflow-y:scroll; overflow-x:hidden;" contenteditable="true"> </div>
<span class="word_count" id="good"></span>
Thanks in advanced!
This is causing an infinite loop if (new Number(word_count) < 0) {.
Your code is a mess altogether. Just study and start with more basic concepts and start over. If you want to describe your project to me in a comment, I would be glad to show you a good, clean, readable approach.
Update:
Part of having a good architecture in your code is to keep different parts of your logic separate. No part of your code should know about or use anything that isn't directly relevant to it. Notice in my word counter that anything it does it immediately relevant to its word-counter-ness. Does a word counter care about what happens with the count? Nope. It just counts and sends the result away (wherever you tell it to, via the callback function). This isn't the only approach, but I just wanted to give you an idea of how to approach things more sensefully.
Live demo here (click).
/* what am I creating? A word counter.
* How do I want to use it?
* -Call a function, passing in an element and a callback function
* -Bind the word counter to that element
* -When the word count changes, pass the new count to the callback function
*/
window.onload = function() {
var countDiv = document.getElementById('count');
wordCounter.bind(countDiv, displayCount);
//you can pass in whatever function you want. I made one called displayCount, for example
};
var wordCounter = {
current : 0,
bind : function(elem, callback) {
this.ensureEditable(elem);
this.handleIfChanged(elem, callback);
var that = this;
elem.addEventListener('keyup', function(e) {
that.handleIfChanged(elem, callback);
});
},
handleIfChanged : function(elem, callback) {
var count = this.countWords(elem);
if (count !== this.current) {
this.current = count;
callback(count);
}
},
countWords : function(elem) {
var text = elem.textContent;
var words = text.match(/(\w+\b)/g);
return (words) ? words.length : 0;
},
ensureEditable : function(elem) {
if (
elem.getAttribute('contenteditable') !== 'true' &&
elem.nodeName !== 'TEXTAREA' &&
elem.nodeName !== 'INPUT'
) {
elem.setAttribute('contenteditable', true);
}
}
};
var display = document.getElementById('display');
function displayCount(count) {
//this function is called every time the word count changes
//do whatever you want...the word counter doesn't care.
display.textContent = 'Word count is: '+count;
}
I would do probably something like this
http://jsfiddle.net/6WW7Z/2/
var wordsLimit = 50;
$('#group_3_1').click(function () {
wordsLimit = 200;
wordCount();
});
$('#group_3_2').click(function () {
wordsLimit = 600;
wordCount();
});
$('.message1').keydown(function () {
wordCount();
});
function wordCount() {
var text = $('.message1').text(),
textLength = text.length,
wordsCount = 0,
wordsRemaining = wordsLimit;
if(textLength > 0) {
wordsCount = text.replace(/[^\w ]/g, '').split(/\s+/).length;
wordsRemaining = wordsRemaining - wordsCount;
}
$('.word_count')
.html(wordsRemaining + " words remaining...")
.attr('id', (parseInt(wordsRemaining) < 0 ? 'bad' : 'good'));
};
wordCount();
It's not perfect and complete but it may show you direction how to do this. You should use change event on checkboxes to change wordsLimit if checked/unchecked. For styling valid/invalid words remaining message use classes rather than ids.
I think you should use radio in place of checkboxes because you can limit 200 or 600 only at a time.
Try this like,
wordCount();
$('input[name="entry.3.group"]').click(function () {
wordCount();
$('.word_count').html($(this).data('val') + " words remaining...");
});
$('.message1').keyup(function () {
wordCount();
});
function wordCount() {
var q = $('input[name="entry.3.group"]:checked').data('val');
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0) var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
try {
if (Number(word_count) < 0) {
$(".word_count").attr("id", "bad");
} else {
$(".word_count").attr("id", "good");
}
} catch (error) {
//
}
};
Also you can add if your span has bad id then key up should return false;
See Demo

Jquery. replace link if not found

I am a newbie and I have inherited some nasty jquery code. I am trying to find a way so that if an error is found then it replaces the string with another string. This is the original code..
W.load = function (b) {
var c, d, g = W.prep; S = ! 0, Q = ! 1, O = x[P], b || _(a.extend(J, a.data(O, e))), ba(l), ba(h, J.onLoad), J.h = J.height? Z(J.height, "y") - M - K: J.innerHeight && Z(J.innerHeight, "y"), J.w = J.width? Z(J.width, "x") - N - L: J.innerWidth && Z(J.innerWidth, "x"), J.mw = J.w, J.mh = J.h, J.maxWidth &&(J.mw = Z(J.maxWidth, "x") - N - L, J.mw = J.w && J.w < J.mw? J.w: J.mw), J.maxHeight &&(J.mh = Z(J.maxHeight, "y") - M - K, J.mh = J.h && J.h < J.mh? J.h: J.mh), c = J.href, V = setTimeout(function () {
B.show()
},
100), J.inline?(Y().hide().insertBefore(a(c)[0]).one(l, function () {
a(this).replaceWith(z.children())
}), g(a(c))): J.iframe? g(" "): J.html? g(J.html): $(c)?(a(Q = new Image).addClass(f + "Photo").error(function () {
//J.title = ! 1, g(Y("Error").text("This image could not be loaded"))
J.title = ! 1, a(this).href.replace('http://www.old.com','http://www.new.com');
}).load(function () {
var a; Q.onload = null, J.scalePhotos &&(d = function () {
Q.height -= Q.height * a, Q.width -= Q.width * a
},
J.mw && Q.width > J.mw &&(a =(Q.width - J.mw) / Q.width, d()), J.mh && Q.height > J.mh &&(a =(Q.height - J.mh) / Q.height, d())), J.h &&(Q.style.marginTop = Math.max(J.h - Q.height, 0) / 2 + "px"), x[1] &&(P < x.length - 1 || J.loop) &&(Q.style.cursor = "pointer", Q.onclick = function () {
W.next()
}), m &&(Q.style.msInterpolationMode = "bicubic"), setTimeout(function () {
g(Q)
},
I have changed the code to this..
J.title = ! 1, a(this).href.replace('http://www.old.com','http://www.new.com');
But its not working. Ggr! Any help would be greatly appriciated. :)
UPDATE*
The code above is the complete code for the section I am working in..
UPDATE #2
This answer works but I need to do...
a(this).attr('src', function(i, current){
if ( i === 'http://www.old.com'){
return current.replace('http://www.old.com','http://www.new.com');
}
else if ( i === 'http://www.older.com'){
return current.replace('http://www.older.com','http://www.new.com');
}
else ();
})
This isn't working!! Help!!
Try
this.href.replace('http://old.com/' , 'http://new.com/');
If you want to change the actual attribute to a new one on the current element then
this.href = this.href.replace('http://old.com/' , 'http://new.com/');
If you are inside a handler that refers to an <a> element then this refers to that object and you do not need to make a jquery object out of it, to access its properties.. so this.href will refer directly to the href property of the link.
Disclaimer: That is obfusated/encoded script and you should better find the original from which this was produced.. This code makes no sense and our suggestion are really in the blind..
From a first look it seems the this is an image and not a link, so if you want to show a new image then you would need to change the src attribute and not the href which does not exist on images..
a(this).attr('src', function(i, current){ return current.replace('http://www.old.com','http://www.new.com');})
But you should also do a console.log(a.fn.jquery) in there to make sure that a is a reference to jQuery
Do you need to do a replace ? If you just want to change the url then you can just do.
J.title = ! 1, $(this).attr('href', 'http://new.com/*');
Which will replace the current url to the new url given.

Categories