JS Class and overriding the JQuery event handlers - javascript

This should be simple, but for reason I can't quite fathom it doesn't work and - more importantly - I can't find the right question to ask of Google!
What I want to do is prototype an event binder for a JS class as per below, what actually happens is nothing, unless I call .bind() directly on the box object.
function Box()
{
this.Width = 200;
this.Height = 200;
this.WrapperClass = "boxWrapper";
this.TitleClass = "boxTitle";
this.ContentClass = "boxContents";
this.Title = "This is a box";
this.Content = "This is some box contents";
}
Box.prototype.Html = function()
{
var box = $('<div></div>').addClass(this.WrapperClass);
box.append($("<div></div>").addClass(this.TitleClass).append(this.Title));
box.append($("<div></div>").addClass(this.ContentClass).append(this.Content));
box.width(this.Width);
box.height(this.Height);
return box.outerHTML();
}
Box.prototype.Bind = function(event, eventDelegate)
{
this.bind(event, eventDelegate);
}
function clickDelegate(message)
{
alert(message);
}
$(document.ready(function() {
var box = $(new Box().Html());
box.Bind('click', clickDelegate('text'));
$('body').append(box);
}

You have to append box before binding events.
I have created a little fiddle starting with your code and debugging it.
FYI : jQuery object has no method outerHTML, So I've embedded the newly created div in one other.
I've made several changes to your code that's why I'm not posting it here.

Related

Javascript hiding and showing dynamic content of a div

Currently I hide and show the content of a div like this:
var header = null;
var content = null;
var mainHolder = null;
var expandCollapseBtn = null;
var heightValue = 0;
header = document.getElementById("header");
content = document.getElementById("content");
mainHolder = document.getElementById("mainHolder");
expandCollapseBtn = header.getElementsByTagName('img')[0];
heightValue = mainHolder.offsetHeight;
header.addEventListener('click', handleClick, false);
mainHolder.addEventListener('webkitTransitionEnd',transitionEndHandler,false);
function handleClick() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
mainHolder.style.height = "26px";
content.style.display = "none";
}
else
{
mainHolder.style.height = heightValue + "px";
}
}
function transitionEndHandler() {
if(expandCollapseBtn.src.search('collapse') !=-1)
{
expandCollapseBtn.src = "expand1.png";
}
else{
expandCollapseBtn.src = "collapse1.png";
content.style.display = "block";
}
}
This is fine if the content is static, but I'm trying to populate my div dynamically like so.
This is called from an iphone application and populates the div with a string.
var method;
function myFunc(str)
{
method = str;
alert(method);
document.getElementById('method').innerHTML = method;
}
I store the string globally in the variable method. The problem I am having is now when I try expand the div I have just collapsed there is nothing there. Is there some way that I could use the information stored in var to repopulate the div before expanding it again? I've tried inserting it like I do in the function but it doesn't work.
Does anyone have any ideas?
to replicate:
Here is the jsfiddle. jsfiddle.net/6a9B3 If you type in text between
here it will work fine. I'm not sure
how I can call myfunc with a string only once in this jsfiddle, but if
you can work out how to do that you will see it loads ok the first
time, but when you collapse the section and attempt to re open it, it
wont work.
If the only way to fix this is using jquery I dont mind going down that route.
is it working in other browsers?
can you jsfiddle.net for present functionality because it is hard to understand context of problem in such code-shoot...
there are tonns of suggestions :) but I have strong feeling that
document.getElementById('method')
returns wrong element or this element not placed inside mainHolder
update: after review sample in jsfiddle
feeling about wrong element was correct :) change 'method' to 'info'
document.getElementById('method') -> document.getElementById('info')
I think you want to use document.getElementById('content') instead of document.getElementById('method') in myFunc.
I really see nothing wrong with this code. However, a guess you could explore is altering the line
content.style.display = "none";
It might be the case that whatever is displaying your html ( a webview or the browser itself) might be wiping the content of the elemtns, as the display is set to none

Onclick - Multiple JavaScript Queries

I've read and tried numerous suggestions from Stack Overflow but none worked for me, forcing me to ask in person.
Currently I use this code to show and hide some content, the id tb1 is the div tag my content is wrapped in.
<input type="button" value="Information" onclick="javascript:sizeTbl('block');" />
(<i>Close</i>)
The button is "Information" and I've added a clickable link that closes the content, because I can't get the button to register the javascript:sizeTbl('none');">(<i>Close</i>)
Can someone please tell me how to do this, I've tried simply adding the javascript:sizeTbl('none');">(<i>Close</i>) after the first onclick command like so:
onclick="javascript:sizeTbl('block');javascript:sizeTbl('none');"
but it doesn't work and I've also tried the below linked fixes but to no avail.
How to call multiple JavaScript functions in onclick event?
Two onClick actions one button
In case it's needed here is the main JS that defines tb1 etc.. I've also tried adding a new function directly in to that script (as I thought calling tb1 outside might cause an issue)
function sizeTbl(h) {
var tbl = document.getElementById('tbl');
tbl.style.display = h;
}
function sizeTb2(h) {
var tb2 = document.getElementById('tb2');
tb2.style.display = h;
}
function sizeTb3(h) {
var tb3 = document.getElementById('tb3');
tb3.style.display = h;
}
function sizeTb4(h) {
var tb4 = document.getElementById('tb4');
tb4.style.display = h;
}
$('#toggle-view').on('click', function()
{
var button = $(this);
if ( button.hasClass('view-page') )
{
ViewPage();
button.removeClass('view-page');
}
else
{
ViewMenu();
button.addClass('view-page');
}
});

onmouseout and onmouseover

I am working on homework that involves working with javascript. Part of my homework assignment is to use the event handlers onmouseout and onmouseouver. What is supposed to happen when the user hovers over a specific div element, the font size grows by 25%, and when the user mouses out of the div element, the font size goes back to normal. My question is, is it possible to incorporate both an onmouseover function and an onmouseout function into one function? Somehow that is what my teacher wants us to do. I have this started so far.
function FontSize(x)
{
x.style.fonstSize = large;
}
I'm also thinking this isnt the correct code to make the font 25% larger, but I'm not sure how to really incorporate an onmouseout in this function.
As a teacher myself, I am 99% sure that by "one function" the instructor means one general-purpose function to change the font size, not one function which uses conditional statements to work backwards and figure out whether it should be doing onmouseout or onmouseover.
Your script should contain:
function resize(elem, percent) { elem.style.fontSize = percent; }
Your HTML should contain:
<div onmouseover="resize(this, '125%')" onmouseout="resize(this, '100%')"
Text within div..
</div>
Note: Situations such as here, are exactly why JavaScript has the keyword "this"--to save us from needing to use complicated document.getElementById() statements.
You can use "%" property for controlling font-size as described here with the following code.
document.getElementById("div1").onmouseover = function() {
document.getElementById("div1").style.fontSize = "125%"
};
document.getElementById("div1").onmouseout = function() {
document.getElementById("div1").style.fontSize = "100%";
};
Here is the working jsfiddle : http://jsfiddle.net/LxhdU/
Yes you can. Call the same function on both events, and pass a parameter to indicate whether the fontsize should increase or decrease.
ChangeFontSize = function(element, shouldIncreaseFontsize)
{
var small=14;
var large = small * 1.25;
if(shouldIncreaseFontsize) {
element.style.fontSize = large + "px";
}
else {
element.style.fontSize = small + "px";
}
}
http://jsfiddle.net/TMHbW/1/
I'd do something simple like the following. The large and small values can be whatever you need them to be for the font size to work or they can be variables you've defined in prior code.
Demo: http://jsfiddle.net/lucuma/EAbYn/
function doHover(e) {
if (e.type=='mouseover') {
this.style.fontSize = "large";
} else {
this.style.fontSize = "small";
}
}
var el = document.getElementById('myelement')
el.onmouseout =doHover;
el.onmouseover=doHover;
It is possible you do not need to call both the events on the element explicitly instead extension you create will do that.Extend the Element's prototype. Jquery also does similar to this.
Ref Prototype
See Fiddle:- http://jsfiddle.net/4fs7V/
Element.prototype.hover= function( fnOver, fnOut ) {
this.onmouseover=fnOver;
this.onmouseout=fnOut || fnOver;
return this;
};
document.getElementById('test').hover(function(){
//do your mouseover stuff
},
function(){
//do your mouseout stuff
});
Update
Same can be achieved with just one function too:-
Hover me
.largeFont {
font-size:125%;
}
Element.prototype.hover = function (fnOver, fnOut) {
this.onmouseover = fnOver;
this.onmouseout = fnOut || fnOver;
return this;
};
document.getElementById('test').hover(changeMe);
function changeMe()
{
if(this.hasAttribute('class'))
{
this.removeAttribute('class');
}
else
{
this.setAttribute('class', 'largeFont');
}
}

Set onCLick callback inside object?

I have a carousel object, with images and a pager. The problem is I can't set the onClick to the pager. I'm obviously missing something here but I don't know what.
The error when I click in a pager item is:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'scrollCarouselTo'
I set my onclick
carouselDots.on('click',function(){
this.scrollCarouselTo(1,5); // <-- problem lies here, how can i call this method?
});
and the scrollTo method
this.scrollCarouselTo=function(dotIndex, numDots)
{
//H_SCROLL.scrollToElement("#carouselItem"+dotIndex, 300);
H_SCROLL.scrollToPage(dotIndex, 0 , 300);
this.highlightCarouselDot(dotIndex, numDots);
}
Last, on my HTML file this is how I set it:
var tempCarousel = new Carousel();
tempCarousel.initialize(params,cont,scrollContainer);
My Carousel class: (parts of it that i think are relevant)
function Carousel() {
var container;
var pager;
var opt;
var thisCarousel;
//render the correct number of dots and highlight the indexed one
this.highlightCarouselDot=function(dotIndex, numDots)
{
var ui_str="";
console.log("numDots" + numDots);
for (var i=0;i<numDots;i++)
{
if (i==dotIndex)
ui_str+='<div class="carouselDot selected" id="carouselDot'+i+'"></div>';
else
ui_str+='<div class="carouselDot" id="carouselDot'+i+'"></div>';
}
console.log(ui_str);
console.log(pager);
pager.html(ui_str);
var carouselDots = $(pager.selector + " .carouselDot");
var dotSelected = $(pager.selector + " .selected");
carouselDots.css('background',opt.pagerImage);
carouselDots.width(opt.pagerSize);
carouselDots.height(opt.pagerSize);
carouselDots.on('click',function(){ //replace with touch
this.scrollCarouselTo(0,5);
});
dotSelected.css('background',opt.pagerSelectedImage);
}
this.scrollCarouselTo=function(dotIndex, numDots)
{
//H_SCROLL.scrollToElement("#carouselItem"+dotIndex, 300);
H_SCROLL.scrollToPage(dotIndex, 0 , 300);
this.highlightCarouselDot(dotIndex, numDots);
}
}
Thank you!
You are having trouble understanding where the scope is changing in your code. Yes this refers to the object you are in, but when you assign an event handler such as onclick, that function is run in the scope of the UI element that was clicked. This means that in your onclick code, this refers to the html object that was clicked, and not the highlightCarouselDot object.
One common solution to this problem is to use an extra variable to store the value of this.
var self = this;
at the start of your object, that way you can refer to self within your event handlers when you want to refer to the outside object.

How to pass an array to an user defined object or convert non-OO code to OO? javascript

I really have trouble with OO coding in js. I have written a piece of code which rotates through 3 divs, and pauses on hover of any div. This code is just regular js using an array/json as the input. the code is a bit long so sorry about that. I just need some guidance on how I can convert this primitive code to a better form, as in OO and encap. When I tried myself I could not pass the slides array/json to my defined object. Is there a trick or guideline i can follow on how to rewrite this to a better form?
Edit - What is a good guideline to follow so I can rewrite this with objects instead of global variables and loose functions
var slideIndex = 0;
var prevIndex = 0;
var t;
function initPromo(){
sortSlides();
nextPromo();
addListeners();
}
function addListeners(){
for(var i=0; i<slides.length; i++)
$(slides[i].el).hover(function(){ stopPromo(); }, function(){ resumePromo(); });
}
function resumePromo(){ startTimer(); }
function stopPromo(){ clearTimeout(t); }
function nextPromo(){
if(slideIndex > 0 || prevIndex > 0) $(slides[prevIndex].el).css("display","none");
$(slides[slideIndex].el).css("display","block");
prevIndex = slideIndex;
slideIndex = (slideIndex<slides.length-1) ? slideIndex+1 : 0;
startTimer();
}
function startTimer(){ t = setTimeout("nextPromo()", 3000); }
function SortByWeight(a,b) { return b.weight - a.weight; }
function SortByWeightFr(a,b) { return b.frWeight - a.frWeight; }
function sortSlides(){
($("body.en").length > 0) ? slides.sort(SortByWeight) : slides.sort(SortByWeightFr);
}
var slides = [
{
el:'#ps1',
weight:1,
frWeight:3
},
{
el:'#ps2',
weight:0.5,
frWeight:6
},
{
el:'#ps3',
weight:4,
frWeight:9
}
];
window.onload = function () {
initPromo();
};
HTML
<body class="en">
<div id="homepageSlides">
<div id="promoSlides">
<div id="ps1">ps1</div><div id="ps2">ps2</div><div id="ps3">ps3</div>
</div>
</div>
</body>
Edit: Early days in OO coding, not asked in the right way
Well your "plain javascript" code is already taking you part way there. The first function you have defined identies the domain object: Promo.
var Promo = function () { };
You have actions on an instance of promo, init, start, stop, resume, etc. These can be defined on the prototype of Promo.
Promo.prototype.init = function() {
// ...
};
It could get a little annoying typing prototype each time, so we could bundle the prototype into a pointer that allows us a lot easier access...
var Promo = function () { };
(function(obj) {
obj.init = function() {
// ...
};
})(Promo.prototype);
So we've got some structure but we need to now separate concerns. Throughout your plain javascript you've got config type data strewn through the code. It's generally a good idea to isolate these bits of data to a single entry point for your object.
obj.init = function(_el) {
// where _el is the base element of this widget
};
I see you're also using jQuery which is good because it gives you a lot of power. One convention I like to use is instead of passing a huge amount of config data into a given widget, I like to give my objects minimal config and let them inspect the HTML to determine additional configuration data. This has the added advantage of if you wanted to add slides in the future or otherwise make changes to the slide content you need'nt worry about changing the JS.
Let's say we were to alter the slide HTML to look like...
<div id="promoSlides">
<div data-type="slide" data-slide-id="1">ps1</div>
<div data-type="slide" data-slide-id="2">ps2</div>
<div data-type="slide" data-slide-id="3">ps3</div>
</div>
Using jQuery we could identify how many slides are present.
obj.init = function(_el) {
this.baseElement = $(_el);
this.slides = this.baseElement.find('*[data-type="slide"]');
};
Now we're passing in minimal config, we've separated out the identification of the slides to the HTML, and we've got a nice pattern for a self-sufficient object. The rest would be to fill in the details (totally untested, but something like this)...
var Promo = function () { };
(function (obj) {
obj.init = function(_el, _delay) {
// Initialize markup
this.baseElement = $(_el);
this.slides = this.baseElement.find('*[data-type="slide"]');
this.slideDelay = _delay;
// Sort slides
// (not sure what's going on here)
// Bind events
this.baseElement
.on('mouseenter', this.stop.bind(this))
.on('mouseleave', this.start.bind(this));
};
obj.start = function() {
this.timer = setInterval(this.advance.bind(this), this.slideDelay);
};
obj.stop = function() {
clearInterval(this.timer);
};
obj.advance = function() {
// Slide the visible slide off screen
// (note: the parent tag will need overflow:hidden)
var visible = this.baseElement.find('*[data-type="slide"]:visible');
visible.animate({ left: '-' + (visible.width()) + 'px' }, 1000);
// Slide the next slide in
var next = visible.next();
next.css('left', this.baseElement.width() + 1).animate({ left: '0' }, 1000);
};
})(Promo.prototype);
Note that I made use of bind which isn't supported yet in older versions of IE.
Its not the converting to object oriented style what is needed for that code there.
Here are issues i see there:
pollution of global scope
mixing fixed CSS rules with Javascript
use of .length attribute within a loop
no event delegation
misplacement of <script> tag, resulting in use of window.onload
creating new jQuery object when it is not needed
use of CSS3 selectors in jQuery calls
no clue how to use setTimeout()
tight coupling to HTML ( id on each slide )

Categories