레이블이 javascript인 게시물을 표시합니다. 모든 게시물 표시
레이블이 javascript인 게시물을 표시합니다. 모든 게시물 표시

2017년 12월 21일 목요일

html javascript radio handler 예제

html javascript radio handler 예제
2017-11-07

썩 좋은 예제는 아님...

전역 namespace 선언하고 
엘레먼트 구분하고 
사용할 엘레먼트 별 이벤트 만들어 넣고
핸들러 영역 구분하고
사용할 핸들러 만들어 넣음. 끝..
jquery 코드 부분은 DOM 기본 셀렉터로 바꾸는게 더 좋다고 생각하지만 귀찮으니까 이 정도로 정리..
멜론 티켓 때 코드를 안 옮겨 놔서 한 번 써봄...

toggle, on 등에 각각 shield 패턴이 들어가야 제대로 된 형태라고 볼 수 있을듯...
setProp 도 역시 jQuery 랩핑이라 그냥 그럼.... .prop 대신 쓸 수 있게 만들면 좋을듯..


var dom = {};
dom.ele = {};
dom.ele.radio = {};
dom.handler = {};
dom.handler.setProp = function(eleId,prop,value){
  $dom[eleId].prop(prop,value);
  //document.getElementById(eleId)[prop] = value;
};
dom.handler.toggle = function(eleId,prop){
    //var value = $dom[eleId].prop(prop) ? false : true;
    var value = document.getElementById(eleId)[prop] ? false : true;
    dom.handler.setProp(eleId,prop,value);
};
dom.ele.radio.toggle = function(eleId){
    var prop = 'checked';
    dom.handler.toggle(eleId,prop);
};
dom.ele.radio.on = function(eleId){
    var prop = 'checked';
    dom.handler.setProp(eleId,prop,true);
};
var $dom = {};
$dom.clazz = {};
var initDom = function() {
  $dom.btn_sms_y = $('#btn_sms_y');
  $dom.btn_sms_n = $('#btn_sms_n');
  $dom.btn_email_y = $('#btn_email_y');
  $dom.btn_email_n = $('#btn_email_n');
};
function init_agree(){
       
       var agreeText ="";
       if(smsBool){
              dom.ele.radio.on('btn_sms_y');
              //$('#btn_sms_y').prop( 'checked', true );
       }else{
              dom.ele.radio.on('btn_sms_n');
              //$('#btn_sms_n').prop( 'checked', true );
       }
       if(emailBool){
              dom.ele.radio.on('btn_email_y');
              //$('#btn_email_y').prop( 'checked', true );
       }else{
              dom.ele.radio.on('btn_email_n');
              //$('#btn_email_n').prop( 'checked', true );
       }
}

2017년 12월 20일 수요일

HTML 에서 Array.forEach 의 한계 -> ie, getElementsByName

HTML 에서 Array.forEach 의 한계 -> ie, getElementsByName

chrome, firefox 등에서는 input 을 getElementsByName 등으로 잡을 경우
Array로 잡아준다.
반면 ie는 HtmlCollection 이라는 것으로 잡아준다.

그래서 forEach는 동작하지 않는다.
HtmlCollection 이 Array 처럼 동작하게 하기 위한 파싱.. 따로 prototype 에 extend 하지는 않고 그냥 함수에 인자로 해당 HtmlCollection을 넣는 식으로 구성했다.
/**
 * for IE HtmlCollection parse to Array
 */
var toArray = function(eles) {
       // shield
       if (eles.forEach && typeof eles.forEach == 'function') {
              return eles;
       }
       
       var ELEMENT_NODE = 1;
       var isElements = (eles.item && (eles.item(0).nodeType == ELEMENT_NODE));
       if (!isElements) {
              if (window.console) {
                     console.log("toArray use only Elements.");
              }
              return eles;
       }
       
       // logic
       var tempItem;
       var resArr = [];
       var htmlCollection = eles;
       for (var i = 0, len = htmlCollection.length; i < len; i++) {
              tempItem = htmlCollection.item(i);
              resArr.push(tempItem);
       };
       return resArr;
}

ele.labes 하면 input 인경우 htmlFor 가 해당 input id와 동일한 label 을 가져온다.
이 것도 ie에는 없다.
인풋의_아이디 가 해당 input 의id라고 할 때
document.querySelector('label[for'+인풋의_아이디+'])
로 가져올 수 있다.

관련 디버깅

NodeList - Web API 참조 문서 | MDN | https://developer.mozilla.org/ko/docs/Web/API/NodeList
HTMLCollection - Web API 참조 문서 | MDN | https://developer.mozilla.org/ko/docs/Web/API/HTMLCollection
Document.getElementsByName() - Web API 참조 문서 | MDN | https://developer.mozilla.org/ko/docs/Web/API/Document/getElementsByName

HTMLCollection - Web API 참조 문서 | MDN | https://developer.mozilla.org/ko/docs/Web/API/HTMLCollection

[크롤링] 유튜브 플레이 리스트 총 시간.

[크롤링] 유튜브 플레이 리스트 총 시간.

https://www.youtube.com/playlist?list=PL9gStYgm-otNJae7Ng5HWre9yfcjdvCE0

와 같이 리스트 목록의 총 재생시간을 구하는 것..

크롤링이라기에는 너무 별로지만... 뭔가 url 넣으면 총 재생시간 나오는 그런 식으로 디벨롭해야 쓸만해질듯....

const looper = (i,ele,list)=>{
//console.log("ee",i,ele);
return {
   idx: i,
   ele: ele.innerText
}
};
const times = document.getElementsByClassName('style-scope ytd-thumbnail-overlay-time-status-renderer');
let res = [];
let i = 0;
for (time of times) {
res.push(looper(i,time,times));
i++;
}
res.reduce((sum,item,idx,list)=>{ const arr = item.ele.split(':'); const currSec = Number(arr[0])*60+Number(arr[1]); return currSec + sum;},0)/(60*60);

2016년 5월 10일 화요일

yyyymmddhhmmss 형태의 timestamp 문자열을 날짜로 변환 ie에서도 되게..

var t = new Date().toISOString().replace(/[-:T]/g,'').replace(/\.(?:\d{3})Z/g,'').replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/,'$1/$2/$3 $4:$5:$6'); //$1-$2-$3 $4:$5:$6 로 하면 ie에서 Date로 바꿔주지 못함. 날짜 구분자를 - 말고 / 로 해줘야 ie에서도 먹힘. === var t = new Date(); //toStirng 계통 /* t.toString() "Mon May 09 2016 12:06:58 GMT+0900 (대한민국 표준시)" t.toISOString() "2016-05-09T03:06:58.440Z" t.toTimeString() "12:06:58 GMT+0900 (대한민국 표준시)" t.toGMTString() "Mon, 09 May 2016 03:06:58 GMT" t.toJSON() "2016-05-09T03:06:58.440Z" t.toUTCString() "Mon, 09 May 2016 03:06:58 GMT" t.toLocaleTimeString() "12:06:58 PM" t.toLocaleString() "5/9/2016, 12:06:58 PM" t.getTime() 1462763218440 */ var q = t.toISOString().replace(/[-:T]/g,'').replace(/\.(?:\d{3})Z/g,''); var qqq = q.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/,'$1-$2-$3 $4:$5:$6'); var tttt = new Date(qqq);




// timestamp 문자열을 날짜로 변환 ie에서도 되게.. yyyymmddhhmmss | since 16-05-10

2016년 3월 29일 화요일

[스크랩]자바스크립트 중복 제거 소스코드

How do I check if an array has duplicate values?
If more than 1 element of the same exist, then return true. Otherwise, return false.
['hello','goodbye','hey'] //return false because no duplicates exist
['hello','goodbye','hello'] // return true because duplicaets exist
shareedit

marked as duplicate by Brian Roachmu is too shortJoseph SilberSasha ChedygovBen AlpertSep 11 '11 at 6:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
   
   
I don't want a list of duplicates removed. I just want to know true or false if a list has duplicates in it. – user847495 Sep 11 '11 at 6:08 
   
The accepted answer for the exact same question you asked is your answer.stackoverflow.com/questions/840781/… – Brian Roach Sep 11 '11 at 6:28 
   
1 
This question is not a duplicate. Since @user847495 simply wants to check if duplicates exists, the solution is faster/easier than what's needed to find all occurrences of duplicates. For example, you can do this:codr.io/v/bvzxhqm – alden Sep 26 '15 at 16:32 

3 Answers

up vote26down voteaccepted
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:
function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}
We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using Object.prototype.hasOwnProperty.call to see if that value has been spotted already; if so, we bail out of the loop and return true. (We don't use valuesSoFar.hasOwnProperty directly because that would break if the array contained "hasOwnProperty" as a string.)

If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}
The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of hasOwnProperty, instead getting an O(n) lookup time of indexOf.
shareedit

2015년 7월 22일 수요일

[스크랩]DOM 링크 열기 제어. 새 창, 현재 페이지, 부모 페이지

DOM 링크 열기 제어. 새 창, 현재 페이지, 부모 페이지

1. 현재페이지에 부를때
onclick="location.href='링크 주소'"

1-1. 새 창에 열때
onclick="window.open('링크 주소')"

2. 상위 프레임에 부를때
onclick="parent.location.href='링크 주소'"

스크랩일: 15-07-22
출처: http://technote.co.kr/php/technote1/board.php?board=memberqna&command=body&no=13364
이름아이콘 YunHu
2008-05-26 20:58
선택된 답변입니다.

2015년 5월 22일 금요일

javascript local storage 활용하기

javascript local storage 활용하기

//담을 때 ('storage_name').set_storage({ key: '꺼내쓸storage_key', val:{ 꺼낼값: JSON.stringify('{"key":"val","key2":"val22"}') } });
//꺼낼 때 var result = ('storage_name').get_storage({key:'꺼내쓸storage_key'});

2015년 4월 6일 월요일

lesscss 정의 및 다운로드 등

lesscss란 무엇인가?

출처: http://opentutorials.org/course/277/1748
css는 html을 꾸며주는 언어입니다. 정보와 표현을 분리해주는 언어로 많은 장점을 가지고 있습니다. 하지만 단점도 있는데요. 이를테면 작성하기는 쉽지만, firebug와 같은 도구 없이는 유지보수하는 것이 매우 어렵습니다. 또 동적인 언어의 특징인 변수나 함수와 같은 특성을 가지고 있지 않기 때문에 많은 양의 코드가 동원되기도 합니다.
이런한 문제를 해결하기 위해서 기술 중의 하나가 lesscss입니다. lesscss를 보다 간결하고 유지보수하기 쉬운 css를 만들 수 있습니다.
lesscss와 유사한 기술로는 sass가 있습니다.

이 문서에 대해서

대상

  • html/css에 대한 기초적인 지식을 알고 있는 분들
  • css를 효율적으로 관리하고 싶은 분들

기존의 CSS를 lesscss로 변환하기

변수

변수를 사용하면, 이곳저곳에서 사용하는 값을 한 곳에 넣어둘 수 있습니다. 그리고 스타일 시트 전체에서 사용할 수 있죠. 그래서 무언가 고쳐야 할 때에, 변수 부분의 코드 한 줄만 바꾸면 되어서 작업이 편해집니다.

LESS

1
2
3
4
5
6
7
8
@color: #4D926F;
#header {
color: @color;
}
h2 {
color: @color;
}

컴파일한 CSS

1
2
3
4
5
6
#header {
color: #4D926F;
}
h2 {
color: #4D926F;
}

믹스인 (Mixins)

믹스인(Mixin)은 한 클래스 안에서 하나의 속성 이름으로 지정하는 방식을 통해 다른 클래스의 모든 속성들을 포함시킬 수 있게 해줍니다. 이것은 마치 변수들 같지만 사실은 클래스 전체를 의미합니다. 믹스인은 또한 함수처럼 변수도 받아들이기도 합니다. 아래의 예시를 보세요.

LESS

1
2
3
4
5
6
7
8
9
10
11
12
.rounded-corners (@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
#header {
.rounded-corners;
}
#footer {
.rounded-corners(10px);
}

컴파일한 CSS

1
2
3
4
5
6
7
8
9
10
#header {
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
#footer {
border-radius: 10px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
}

중첩 또는 포함에 관한 규칙

CSS 속성 상속을 위해 긴 선택자(selector)를 만드는 방법 대신, LESS에서는 한 선택자를 다른 선택자 안에 포함시킬 수 있습니다. 이를 통해 CSS 속성 상속을 훨씬 더 간결하게, 그리고 스타일 시트를 짧게 만들 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
#header {
h1 {
font-size: 26px;
font-weight: bold;
}
p { font-size: 12px;
a { text-decoration: none;
&:hover { border-width: 1px }
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#header h1 {
font-size: 26px;
font-weight: bold;
}
#header p {
font-size: 12px;
}
#header p a {
text-decoration: none;
}
#header p a:hover {
border-width: 1px;
}

함수와 연산

스타일시트 안의 어떤 요소들이 다른 요소들에 대해 비례하나요? 연산 (operation)은 속성값과 색상값들을 더하고, 빼고, 곱하고 나누게 하는 것을 통해 속성들 사이의 복잡한 관계들을 정의할 수 있게 해줍니다. 함수는 자바스크립트 코드와 일대일 대응을 시켜 당신이 원하는 속성값들은 무엇이든지 생성해 낼 수 있게 합니다.

LESS

1
2
3
4
5
6
7
8
9
10
11
12
13
@the-border: 1px;
@base-color: #111;
@red: #842210;
#header {
color: @base-color * 3;
border-left: @the-border;
border-right: @the-border * 2;
}
#footer {
color: @base-color + #003300;
border-color: desaturate(@red, 10%);
}

컴파일된 CSS

1
2
3
4
5
6
7
8
9
#header {
color: #333;
border-left: 1px;
border-right: 2px;
}
#footer {
color: #114411;
border-color: #7d2717;
}

다른 언어로 보기

  • 러시아어: http://lesscss.ru
  • 중국어: http://lesscss.net
  • 일본어: http://less-ja.studiomohawk.com/
  • 벨라루스어: http://www.designcontest.com/show/lesscss-be

About

LESS는 Alexis Sellier가 개발했습니다. 그는 cloudhead라는 닉네임으로 좀 더 널리 알려져 있습니다.
powered by LESS
Copyright © Alexis Sellier 2010-2012

출처: http://opentutorials.org/course/277/1748

크롬 에서 번역 옵션 뜨는 거 막는 방법

버그 같은게 아니고 저 옵션의 기본 값이 제공으로 바뀐듯... 번역 옵션 제공을 비활성화하면 안 뜸. Chrome에서 웹페이지 번역 모르는 언어로 작성된 페이지를 방문할 때 다음 단계에 따라 Chrome이 페이지를 번역하도록 할 수 있습...