Combining click and dbclick - javascript

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();
});

Related

Trigger a event when the user is on the page

I have this code
$(document).ready(function(){
var fade_in = function(){
$(".quote").fadeIn();
}
setTimeout(fade_in, 2000);
var fade_out = function() {
$(".quote").fadeOut();
}
setTimeout(fade_out, 10000);
});
What it does is that the div "quote" slowly fades in, stays for a few seconds and then fades out. What I want is that all this happens when the user is on the page, if you're not in the page,the text fades in, fades out and you miss it. How can I do that?
There are two ways
First : (bit old)
$(document).ready(function() {
window.onfocus = function() {
var fade_in = function() {
$(".quote").fadeIn();
}
setTimeout(fade_in, 2000);
var fade_out = function() {
$(".quote").fadeOut();
}
setTimeout(fade_out, 10000);
};
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote">quote</div>
Second :
function getHiddenProp() {
var prefixes = ['webkit', 'moz', 'ms', 'o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++) {
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
function isHidden() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
document.addEventListener(evtname, visChange);
}
function visChange() {
var txtFld = document.getElementById('visChangeText');
if (txtFld) {
if (!isHidden()) {
var fade_in = function() {
$(".quote").fadeIn();
}
setTimeout(fade_in, 2000);
var fade_out = function() {
$(".quote").fadeOut();
}
setTimeout(fade_out, 10000);
};
}
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote">quote</div>
This will execute when page div visible
$(document).ready(function(){
$( "div:visible" ).click(function() {
$( this ).css( "background", "yellow" );
});
});

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.

condense multiple instances into one

i've got a little code in in my main.js file that i've been using for activating various popover [bootstrap] buttons throughout the page.
// popover 1
var $btn1 = $('#btn1');
$btn1.data('state', 'hover');
var enterShow = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('show');
}
};
var exitHide = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('hide');
}
};
var clickToggle = function () {
if ($btn1.data('state') === 'hover') {
$btn1.data('state', 'pinned');
} else {
$btn1.data('state', 'hover')
$btn.popover('hover');
}
};
$btn1.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
// popover 2
var $btn2 = $('#btn2');
$btn2.data('state', 'hover');
var enterShow = function () {
if ($btn2.data('state') === 'hover') {
$btn2.popover('show');
}
};
var exitHide = function () {
if ($btn2.data('state') === 'hover') {
$btn2.popover('hide');
}
};
var clickToggle = function () {
if ($btn2.data('state') === 'hover') {
$btn2.data('state', 'pinned');
} else {
$btn2.data('state', 'hover')
$btn.popover('hover');
}
};
$btn2.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
but the more buttons (popovers) i add, the more instances of this i have to keep putting in the main.js.
QUESTION:
is there a multiplier i can use to achieve this result with just one instance of the code instead of an instance for each popover.
Question is not very clear to me but if you just want to make the same initialisation on differents buttons, then just create a function for it.
function initPopover(selector){
var $btn1 = $(selector);
$btn1.data('state', 'hover');
var enterShow = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('show');
}
};
var exitHide = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('hide');
}
};
var clickToggle = function () {
if ($btn1.data('state') === 'hover') {
$btn1.data('state', 'pinned');
} else {
$btn1.data('state', 'hover')
$btn.popover('hover');
}
};
$btn1.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
}
Instead of using a fixed variable name inside the event handler, use $(this), which references the element the handler is bound to:
$('#btn1 #btn2') // <- note that I'm selecting both buttons
.data('state', 'hover')
.popover({trigger: 'manual'})
.on({
mouseenter: function() {
if ($(this).data('state') === 'hover') {
$(this).popover('show');
}
},
mouseleave: function() {
if ($(this).data('state') === 'hover') {
$(this).popover('hide');
}
},
click: function () {
if ($(this).data('state') === 'hover') {
$(this).data('state', 'pinned');
} else {
$(this).data('state', 'hover')
$(this).popover('hover');
}
}
});
I recommend to read the jQuery tutorial to learn more about event handlers, where it says:
In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword this. To turn the DOM element into a jQuery object that we can use jQuery methods on, we simply do $( this ) [...]

I was trying to make a news ticker. But there's an error when mouse leaves after hover

After Mouse Leave the ticker starts to move at a very high speed. Don't know what's the error.
Javascript:
$('#tick2').html($('#tick').html());
var temp=0,intervalId=0;
$('#tick li').each(function() {
var offset=$(this).offset();
var offsetLeft=offset.left;
$(this).css({'left':offsetLeft+temp});
temp=$(this).width()+temp+10;
});
$('#tick').css({'width':temp+40, 'margin-left':'20px'});
temp=0;
$('#tick2 li').each(function(){
var offset=$(this).offset();
var offsetLeft=offset.left;
$(this).css({'left':offsetLeft+temp});
temp=$(this).width()+temp+10;
});
$('#tick2').css({'width':temp+40,'margin-left':temp+40});
function abc(a,b) {
$('#outer').mouseenter(function() { window.clearInterval(intervalId);intervalId=0; });
$('#outer').mouseleave(function() { start(); })
var marginLefta=(parseInt($("#"+a).css('marginLeft')));
var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
$("#"+a).css({'margin-left':(marginLefta-1)+'px'});
} else {
$("#"+a).css({'margin-left':temp});
}
if((-marginLeftb<=$("#"+b).width())){
$("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
} else {
$("#"+b).css({'margin-left':temp});
}
}
function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
start();
You can check the working demo here : http://jsfiddle.net/mstoic/juJK2/
Well, you nearly blew up my browser! Can you try this instead:
function abc(a,b) {
var marginLefta=(parseInt($("#"+a).css('marginLeft')));
var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
$("#"+a).css({'margin-left':(marginLefta-1)+'px'});
} else {
$("#"+a).css({'margin-left':temp});
}
if((-marginLeftb<=$("#"+b).width())){
$("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
} else {
$("#"+b).css({'margin-left':temp});
}
}
function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
$(function(){
$('#outer').mouseenter(function() { window.clearInterval(intervalId); });
$('#outer').mouseleave(function() { start(); })
start();
});
Working fiddle: http://jsfiddle.net/juJK2/1/
You should only bind your event handlers once, not every time you enter abc();

How would I toggle the state of a setInterval function in jQuery?

I want to be able to click a an element with an id of pause to start a count of the elements in a time object and if I re click the pause it will stop it and reclick start it exactly like the toggle feature in JQuery but with a setInteval function how would I go about doing this?
$("#pause").click(function(ffe) {
if(on == true) {
on = false
alert("on");
}
else {
on = true;
alert("off");
}
if(on == false) {
setInterval(function() {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}, 100);
}
else {
alert("Error");
}
});
A classic technique is to use a single master setInterval loop and simply use if..else logic to determine what needs to run. This is how a lot of javascript games work:
var on = true;
// Our master scheduler:
setInterval(function() {
if (on) {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}
}, 100);
// Code to handle the pause button
$("#pause").click(function(ffe) {
on = !on;
}
You can use the setTimeout function, if you want to run the function once, setInterval runs continuously, try the following:
var on = false;
$("#pause").click(function(ffe) {
if (on) {
on = false;
setTimeout(function() {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}, 100);
} else {
on = true;
}
});
You need to use .clearInterval() to stop the execution.
Here is the code: (THE WORKING DEMO)
$("#pause").click((function () {
var interId = null;
var $ul = $("#timet ul");
return function (e) {
if (interId) {
$(this).text("start");
clearInterval(interId);
interId = null;
} else {
$(this).text("pause");
interId = setInterval(function () {
$ul.append($('<li>').text($('li', $ul).length));
}, 100);
}
};
}()));​

Categories

Resources