suitable substitution in jquery - javascript

With the help of jquery I've done the following for changing the color of the row on clicking a checkbox,all the checkbox is having same class name, the code is working fine, but the requirement in one of our project was to do this using simple pure javascript (no library)
can anyone please tell me some solution for this
$(".cbxSelect").click(function (e) {
if (!$(this).closest('tr').hasClass("myclass")) {
$(this).closest('tr').css('background-color', 'yellow');
$(this).closest('tr').addClass("myclass");
} else {
$(this).closest('tr').css('background-color', 'white');
$(this).closest('tr').removeClass("myclass");
}
});
http://jsfiddle.net/Kph8M/8/

var boxes = document.querySelectorAll('.cbxSelect');
for (var i=boxes.length; i--;) {
boxes[i].addEventListener('change', handler, false);
}
function handler() {
var el = this;
while (el.parentNode) {
el = el.parentNode;
if (el.tagName.toLowerCase() === 'tr') {
break;
}
}
if (el.getAttribute('data-color') != 'yellow') {
el.style.backgroundColor = 'yellow';
el.setAttribute('data-color', 'yellow');
}else{
el.style.backgroundColor = 'white';
el.setAttribute('data-color', 'white');
}
}
FIDDLE

Since you already toggle myclass it makes sense to use it for background color:
.myclass {
background: yellow;
}
and JS:
var checks = document.querySelectorAll('.cbxSelect');
for (var i = 0; i < checks.length; i++) {
checks[i].onchange = function() {
var tr = this.parentNode.parentNode;
if (/\bmyclass\b/.test(tr.className)) {
tr.className = tr.className.replace(/\bmyclass\b/g, '');
}
else {
tr.className += ' myclass';
}
};
}
Demo: http://jsfiddle.net/dfsq/Kph8M/12/

Related

Combining click and dbclick

How I am supposed to combine the below ones into one single working script?
When is clicked once a color picked-up by user appears,click again the color turns in white and when double-clicked appears aqua. It is too long code, I tried to combine them, but I made mistake.
//single click
$('#pixel_canvas').on('click', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'white');
}
});
//double click
$('#pixel_canvas').on('dblclick', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'aqua');
}
});
I'd go something like this:
// Take your actual 'core' code and turn it into a jQuery function:
$.fn.setColor(colorOff){
if( $(this).hasClass("blank") ){
$(this)
.css('background-color', $('#colorPicker').val())
.removeClass('blank');
} else{
$(this)
.addClass('blank')
.css('background-color',colorOff);
}
}
// Now bind the events to the element and pass the color needed for the events:
$('#pixel_canvas')
.on('click','td',function(){
$(this).setColor('white')
})
.on('dblclick','td',function(){
$(this).setColor('aqua')
});
This may help.
function doClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','white');
}
}
function doDoubleClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','aqua');
}
}
var timer = 0;
var delay = 200;
var prevent = false;
$("#pixel_canvas")
.on("click", function() {
timer = setTimeout(function() {
if (!prevent) {
doClickAction();
}
prevent = false;
}, delay);
})
.on("dblclick", function() {
clearTimeout(timer);
prevent = true;
doDoubleClickAction();
});

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

jQuery change opacity of non-matching items

I have the following jquery which has been created with the help of a SO member in a previous question...
var filters = [];
function filterList () {
var classes = '.' + filters.join('.');
$('.test').removeClass('main');
if (classes.length > 1) {
$(classes).addClass('main');
}
}
function removeFilter(ele) {
var len = filters.length,
idx;
for (var i = 0; i < len; i++) {
if (filters[i] === ele) {
idx = i;
break;
}
}
filters.splice(idx, 1);
}
function addFilter(ele) {
if (ele) {
filters.push(ele);
}
}
var selectIt = (function () {
var lastSelect;
return (function (ele) {
if (lastSelect) {
removeFilter(lastSelect);
}
addFilter(ele);
lastSelect = ele;
});
}());
$('.selector').on('change', function (e) {
var val = $(this).val();
selectIt(val);
filterList();
});
$('.mybuttons a').on('click', function (e) {
e.preventDefault();
var el = $(this),
col = el.data('col');
if (el.hasClass('active')) {
removeFilter(col);
} else {
addFilter(col);
}
el.toggleClass('active');
filterList();
});
http://jsfiddle.net/fprL03e5/
I am now trying to modify the code so that when an option is selected, all of the non-matching terms have reduced opacity.
When the page is initially loaded all items should have full opacity until one of the items is selected.
I have tried adding an extra class but can't work out how to have it removed when items are de-selected.
Is this what you're looking to do?
http://jsfiddle.net/fprL03e5/3/
function filterList () {
var classes = '.' + filters.join('.');
$('.test').removeClass('main');
$('.test').css('opacity', '.5');
if (classes.length > 1) {
$(classes).addClass('main').css('opacity', '1');
} else {
$('.test').css('opacity', '1');
}
}

Javascript hover with querySelectorAll

How do such a thing to work:
function getElements(attrib) {
return document.querySelectorAll('[' + attrib + ']');
}
$(window).load(function () {
$(".b1").hover(function () {
$(this).className = 'x';
var elements = getElements('code');
for (var i = 0; i < elements.length; i++) {
if (elements[i] == 'wow') {
elements[i].className = 'blue';
} else {
elements[i].className = 'red';
}
}
}, function () {
$(this).className = 'y';
});
});
http://jsfiddle.net/rc6Pq/10/
I would like hover to "BUTTON HOVER" and then show this elements with atributes "code" in different colors for "wow" and "lol".
Regards and thanks in advance!
What about this version:
function getElements(attrib) {
return $('[' + attrib + ']');
}
$(window).load(function () {
$(".b1").hover(function () {
$(this).className = 'x';
var elements = getElements('code');
getElements('code').addClass('red').filter('[code="wow"]')
.removeClass('red').addClass('blue');
}, function () {
$(this).className = 'y';
});
});
http://jsfiddle.net/rc6Pq/11/
or even better:
var elements = getElements('code'),
wow = getElements('code').filter('[code="wow"]').addClass('blue');
elements.not(wow).addClass('red');
http://jsfiddle.net/rc6Pq/12/

Javascript to add class when checkbox is selected

I have this piece of code:
<div class="quote-box-col14">
<label for="seo" class="quote-service-seo">SEO</label>
<input type="checkbox" name="seo" id="seo" value="Y" class="checkbox-seo" />
</div>
Someone can help with a JavaScript that adds class "selected" to when checkbox is selected?
Thanks
This jQuery will do it:
$('#seo').change(function(){
if($(this).is(":checked")) {
$(this).addClass("checked");
} else {
$(this).removeClass("checked");
}
});
See this jQuery fiddle for a working example.
Edit:
If you need it to work in IE too, use the click event instead:
$('#seo').click(function(){
if($(this).is(":checked")) {
$(this).addClass("checked");
} else {
$(this).removeClass("checked");
}
});
And in pure JavaScript (for HTML5)
document.getElementById ('seo').addEventListener ('click', function (ev) {
ev.target.parentNode.classList[ ev.target.checked ? 'add' : 'remove'] ('selected');
}, false);
There is also a classList.toggle function but there is always a danger that the checkbox and the classList might lose synchronism.
You can infer from this: jQuery toggleClass and check checkbox
But essentially, you can use toggleClass to toggle a specific CSS class:
$("#seo").click(function() {
$(this).toggleClass("cssClassToToggle");
});
Or use addClass to add a new class only:
$("#seo").click(function() {
$(this).addClass("cssClassToToggle");
});
If you are talking a range of checkboxes, you can target with $(":checkbox") too.
Here's pure js that will work for adding and removing the selected class when any checkbox is checked or unchecked.
Working example: http://jsfiddle.net/S9tSS/
var inputs = document.getElementsByTagName("input");
var checkboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
checkboxes.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
for (var j = 0; j < checkboxes.length; j++) {
checkboxes[j].onclick = function() {
if (this.checked == true) {
this.className += " selected";
} else {
removeClassName(this, 'selected');
}
}
}
function removeClassName(e,t) {
if (typeof e == "string") {
e = xGetElementById(e);
}
var ec = ' ' + e.className.replace(/^\s+|\s+$/g,'') + ' ';
var nc = ec;
if (ec.indexOf(' '+t+' ') != -1) {
nc = ec.replace(' ' + t + ' ',' ');
}
e.className = nc.replace(/^\s+|\s+$/g,'');
return true;
}
Sources: ...well... I would post them, but I'm a new use an can't post more than two links.
With jQuery:
$('input[type="checkbox"]').change(function() {
if (this.checked) {
$(this).addClass('checked');
} else {
$(this).removeClass('checked');
}
});
$('#seo').click(function() {
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
}
});
$('#seo').click(function(){
$(this).toggleClass('selected', this.checked);
});

Categories

Resources