Populating div with checkboxes - javascript

I use this code to determine checkbox width and height:
var chk = $('input[type="checkbox"]:first');
chkWidth = chk.innerWidth()
+ parseInt(chk.css('margin-left').replace('px', ''))
+ parseInt(chk.css('margin-right').replace('px', '')); /*IS there better way instead of px replace?? */
chkHeight = chk.innerHeight()
+ parseInt(chk.css('margin-top').replace('px', ''))
+ parseInt(chk.css('margin-bottom').replace('px', ''));
fieldWidth = gamefield.innerWidth();
fieldHeight = gamefield.innerHeight();
Then i try to fill div with the number of checkboxes that exactly fits given div. In fact i get a lot of checkboxes out of div.
http://dl.dropbox.com/u/3473965/jq/tetris.html
http://dl.dropbox.com/u/3473965/jq/tetris.js
Is there anyway to solve this? Thank you!

leaving other things as such, this makes the difference (on FF3.5):
var cols=Math.floor(fieldWidth/chkWidth);
var rows=Math.floor(fieldHeight/chkHeight);
var html='';
for(var i=0;i<=rows;i++) //if yo use i<rows there is space for one more row
{
for(var j=0;j<cols;j++)
{
html +="<input type='checkbox'/>";
}
}
gamefield.html(html);

Related

Any way to prevent losing focus when clicking an input text out of tinymce container?

I've made this tinymce fiddle to show what I say.
Highlight text in the editor, then click on the input text, highlight in tinyMCE is lost (obviously).
Now, I know it's not easy since both, the inline editor and the input text are in the same document, thus, the focus is only one. But is there any tinymce way to get like an "unfocused" highlight (gray color) whenever I click in an input text?
I'm saying this because I have a customized color picker, this color picker has an input where you can type in the HEX value, when clicking OK it would execCommand a color change on the selected text, but it looks ugly because the highlight is lost.
I don't want to use an iframe, I know that by using the non-inline editor (iframe) is one of the solutions, but for a few reasons, i can't use an iframe text editor.
Any suggestion here? Thanks.
P.S: Out of topic, does any of you guys know why I can't access to tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global var was overwritten by the tinymce select dom element of the page itself. I can't execute a tinyMCE command lol.
Another solution:
http://fiddle.tinymce.com/sBeaab/5
P.S: Out of topic, does any of you guys know why I can't access to
tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global
var was overwritten by the tinymce select dom element of the page
itself. I can't execute a tinyMCE command lol.
Well, you can access the tinyMCE variable and even execute commands.
this line is wrong
var colorHex = document.getElementById("colorHex")
colorHex contains input element, not value.
var colorHex = document.getElementById("colorHex").value
now it works ( neolist couldn't load, so I removed it )
http://fiddle.tinymce.com/DBeaab/1
I had to do something similar recently.
First off, you can't really have two different elements "selected" simultaneously. So in order to accomplish this you're going to need to mimic the browser's built-in 'selected text highlight'. To do this, you're going to have to insert spans into the text to simulate highlighting, and then capture the mousedown and mouseup events.
Here's a fiddle from StackOverflow user "fullpipe" which illustrates the technique I used.
http://jsfiddle.net/fullpipe/DpP7w/light/
$(document).ready(function() {
var keylist = "abcdefghijklmnopqrstuvwxyz123456789";
function randWord(length) {
var temp = '';
for (var i=0; i < length; i++)
temp += keylist.charAt(Math.floor(Math.random()*keylist.length));
return temp;
}
for(var i = 0; i < 500; i++) {
var len = Math.round(Math.random() * 5 + 3);
document.body.innerHTML += '<span id="'+ i +'">' + randWord(len) + '</span> ';
}
var start = null;
var end = null;
$('body').on('mousedown', function(event) {
start = null;
end = null;
$('span.s').removeClass('s');
start = $(event.target);
start.addClass('s');
});
$('body').on('mouseup', function(event) {
end = $(event.target);
end.addClass('s');
if(start && end) {
var between = getAllBetween(start,end);
for(var i=0, len=between.length; i<len;i++)
between[i].addClass('s');
alert('You select ' + (len) + ' words');
}
});
});
function getAllBetween(firstEl,lastEl) {
var firstIdx = $('span').index($(firstEl));
var lastIdx = $('span').index($(lastEl));
if(lastIdx == firstIdx)
return [$(firstEl)];
if(lastIdx > firstIdx) {
var firstElement = $(firstEl);
var lastElement = $(lastEl);
} else {
var lastElement = $(firstEl);
var firstElement = $(lastEl);
}
var collection = new Array();
collection.push(firstElement);
firstElement.nextAll().each(function(){
var siblingID = $(this).attr("id");
if (siblingID != $(lastElement).attr("id")) {
collection.push($(this));
} else {
return false;
}
});
collection.push(lastElement);
return collection;
}
As you can see in the fiddle, the gibberish text in the right pane stays highlighted regardless of focus elsewhere on the page.
At that point, you're going to have to apply your color changes to all matching spans.

Issues with text formatting after jQuery

I have used code form here: Overflowed text with html in another div - to get text to flow over in a new div. However, now I have formatting issues with the text.
The first word of every paragraph is somehow followed by a line-break.
You can see an example here: http://jsfiddle.net/hm2yfw61/9/
var currentCol = $('.box:first');
var text = currentCol.html();
currentCol.html('');
text = text.replace(/ (?![^<>]*>)/gi, '%^%');
var wordArray = text.split('%^%');
$.fn.hasOverflow = function () {
var div = document.getElementById($(this).attr('id'));
return div.scrollHeight > div.clientHeight;
};
for (var x = 0; x < wordArray.length; x++) {
var word = wordArray[x];
currentCol.append(word + ' ');
if (currentCol.hasOverflow()) {
currentCol = currentCol.next('.box');
}
}
Does anyone know how I can fix this?
Thanks.
-----UPDATE: I've updated the jsfiddle with the working solutions suggested in reference for others who may face similar problems ------
This might be a bit hacky, but try the following:
Add the following CSS rule
.box > p:first {
display: none;
}
Add "nbsp; " (including the space) at the beginning of each string in .box > p tags.
<p> Jumo handango
Updated Fiddle

Combine Several Similar Variable Declarations

This is a small part of a script I'm working on that generates an eBay listing with the user's photos and text. The script outputs all the code as a string for copying and pasting, as well as rendered HTML/CSS/JavaScript for a preview. For that reason, href and src attributes need to be populated dynamically, since I don't know them in advance. This snippet in particular seems to me to be too redundant. I'm not sure how to go about this other than how I have it currently.
I posted a working piece of this code and a fiddle on CodeReview, hoping to get general suggestions on my code. Since this is a specific issue, I'm posting it here.
Here are the first two statements I have which populate the href to the full-size image:
var fullSizeSrc1 = $('#slide-upload tr:first td:first a').attr('href');
if (fullSizeSrc1) {
fullSizeSrc1 = fullSizeSrc1;
} else {
fullSizeSrc1 = '';
}
var fullSizeSrc2 = $('#slide-upload tr:nth-child(2) td:first a').attr('href');
if (fullSizeSrc2) {
fullSizeSrc2 = fullSizeSrc2;
} else {
fullSizeSrc2 = '';
}
I currently have seven of those, and seven of these (these populate the src attribute for the thumbnails):
var thumbSrc1 = fullSizeSrc1;
if (thumbSrc1) {
thumbSrc1 = thumbSrc1.replace(/files/g, 'files/thumbnail');
} else {
thumbSrc1 = '';
}
Here's a portion of the script that contains the HTML markup to be generated, and populates the proper attributes with the above variables:
'<div id="mblSlide">' +
'<img data-name="one" alt="" src="'+fullSizeSrc1+'">' +
'<img data-name="two" alt="" src="'+fullSizeSrc2+'">' +
'</div>' +
'<div id="mblThumbs">' +
'<img style="border:1px solid #fff;margin:3px" data-name="one" alt="" src="'+thumbSrc1+'">' +
'<img style="border:1px solid #fff;margin:3px" data-name="two" alt="" src="'+thumbSrc2+'">'
'</div>' +
I hope that's clear. If not, please let me know what was unclear and I'll try my best to, ah, clarify :) Thanks in advance for all the great work you guys do.
As mentioned in the comments
if (fullSizeSrc1) {
fullSizeSrc1 = fullSizeSrc1;
}
Doesn't really do anything or change the value of fullSizeSrc1. You should change it to:
if(!(fullSizeSrc1)){
fullSizeSrc1 = '';
}
//or if(fullSizeSrc1 === undefined)
To your original question about not retyping code:
I consider it a tell when you find yourself name different instances of the same type of data as var1, var2, var3, var4. Once you start counting, you should probably consider using an array.
So we have as a start:
var fullSizeSrc = [];
var fss = $('#slide-upload tr:first td:first a').attr('href');
if(!fss){
fss = '';
}
fullSizeSrc.push();
But then we still have the problem of writing the same code 7 times right? You should look at what the difference is between each version of the same code. The first was the variable name, we solved that by using an array.
The second difference is that we indexing into list of child elements. So assuming we have 7 elements to look at 1 .. 7. We can use a simple for loop to cut out the other code.
var fullSizeSrc = [];
var total = 7;
for(var i =1, i <= total; i++){
var fss = $('#slide-upload tr:nth-child('+i+') td:first a').attr('href');
if(!fss){
fss = '';
}
fullSizeSrc.push();
}
But what if we didn't know the list size? Luckily that nth-child jquery function can return a list of all child elements
var fullSizeSrc = [];
var links = $('#slide-upload tr:nth-child(n) td:first a');
$(links).each(funcion(i, a){
var link = $(a).attr('href');
if(!link){
link = '';
}
fullSizeSrc.push(link);
})

detecting a div's position based on it's attaribute

I have three divs and I want to execute a command on a div that happens to be on top of the other divs in a container without referencing it's name or id.I am randomizing the position of the divs and I basically want the div whose height is equal to 10px to change it's color attribute to red when a specific number is generated, whilst the other divs maintain their default color. I have tried the following but I can't think of any way to do this without using the div's id.
var current = 0;
current++;
var topArrtcard = document.getElementById("card-answer");
var topArrtcard1 = document.getElementById("card-answer1");
var topArrtcard2 = document.getElementById("card-answer2");
if(current === 0 ){
topArrtcard.style.color = "red"; // is it possible not use the id in order to make the change
topArrtcard1.style.color = " #996600";
topArrtcard2.style.color = " #996600";
}else if(current === 1 )
{
topArrtcard.style.color = "#996600";
topArrtcard1.style.color = "red";
topArrtcard2.style.color = " #996600";
}else if(current === 2){
topArrtcard.style.color = "#996600";
topArrtcard1.style.color = " #996600";
topArrtcard2.style.color = "red";
}else {
topArrtcard.style.color = "#996600";
topArrtcard1.style.color = " #996600";
topArrtcard2.style.color = "#996600";
}
the variable current increments by 1 each time the page is loaded. I hope this is clear. Thank you in advance.
If you are not opposed to using jQuery (and why would you be? In many ways it's simpler than javascript with much less to type)...
I cannot see from your code (at this moment) what will trigger an event that you can use to do the testing that you want.
However, if something does happen to the DIV, then perhaps you can use that event to make the changes you want. You would reference the changed DIV as this.
Here is an example that looks somewhat similar

Reduce textarea height based on its content

I'm able to increase textarea height as textrows add up (based on this question/answer: Adjust TD height depending on textarea rows).
Now, how do I reduce rows as I remove text? The answer above only adds rows.
If you want it more stable, you can count the linebreaks. So you can be sure that it set exactly the right number of rows:
$('.expand').on('keydown', function(e) {
if(13==(e.keyCode ? e.keyCode : e.which)) {
var rows = $(this).attr('rows');
var rowsNew = parseInt(rows) + 1;
$(this).attr('rows', rowsNew);
}
});
$('.expand').on('keyup', function (e) {
var lines = $('.expand').val().match(/\n/g);
var need = lines ? lines.length + 1 : 1;
var itis = $('.expand').attr("rows");
if(itis!=need) {
$('.expand').attr("rows", need);
}
});
Demo here: http://jsfiddle.net/efhYe/
But if you have jQuery already, you can also use this plugin: http://www.jacklmoore.com/autosize/

Categories

Resources