JQuery Click Handler - javascript

I'm creating a bunch of divs and inserting thumbnail images through a referenced js file using a simple function. Basically i'm trying to assign the click handler to each new div in the loop but for probably syntax reasons it isn't working.
This is my code ( updated )...
function makethumbs() {
for (var i = 0; i < 14; i++) {
var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
newdiv.css({display:'inline',
float:'left',
margin:'2px 2px 0 0',
color:'#000',
fontSize:'18px',
zIndex:0,
html:'P',
background: 'url(' + backgroundUrl + ')'
});
newdiv.click(function() {
$(this).stop(true, true).fadeTo('slow', 0);
});
$('#thumbholder').append(newdiv);
}
$('#arrowright').click(function() {
var L = $('#thumbholder'),
margL = parseInt(L.css('marginLeft'), 10),
newMarg = (margL - 147) + 'px',
anim = {opacity: 1};
anim["marginLeft"] = newMarg;
$('#thumbholder').stop(true, true).animate(anim, 400);
});
}
Theres an extra click handler there too for #arrowright which works fine. Not sure if its a z ordering thing as the clickable arrow div is inside a container which overlays the thumbnail divs if that makes sense.

Why not keep on using jQuery ?
function makethumbs() {
for (var i = 0; i < 14; i++) {
var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
newdiv.css({display:'inline',
float:'left',
margin:'2px 2px 0 0',
color:'#000',
fontSize:'18px',
zIndex:0,
html:'P',
background: 'url(' + backgroundUrl + ')'
});
newdiv.click(function() {
$(this).stop(true, true).fadeTo('slow', 0);
});
$('#thumbholder').append(newdiv);
}
$('#arrowright').click(function() {
var L = $('#thumbholder'),
margL = parseInt(L.css('marginLeft'), 10),
newMarg = (margL - 147) + 'px',
anim = {opacity: 1};
anim["marginLeft"] = newMarg;
$('#thumbholder').stop(true, true).animate(anim, 400);
});
}​
as your main problem is trying to attach a click handler with jQuery syntax to a native JS DOM element.

change newDiv.click to $(newDiv).click since you seem to be using jQuery; however if you want to continue using native javascript you can set an event for the element like so:
newDiv.addEventListener('click',function(){
//you code here
});

Related

Lightbox Jquery on click next image

I am using a mixture of freewall and featherlight plugins to produce a responsive gallery which opens into a lightbox, however, I am having the following issue with trying to get the lightbox to switch to the next image (i + 1) when clicked.
The Lightbox image code enter image description here. What I want to do is to change the img src to i + 1 so it will go to the next image on click.
I also have this project on Github which might help understand: https://github.com/adamianniello/adamianniello.com/blob/master/B%C3%A6b%C3%A6l%C9%99n_Pasadena.html
<script type="text/javascript">
var temp = "<div class='brick' style='width:{width}px;'><a href='#' data-featherlight='i/jpl/{link}.jpg'><img src='i/jpl/{index}.jpg' width='100%'></a></div>";
var w = 1, h = 1, html = '', limitItem = 54;
for (var i = 0; i < limitItem; ++i) {
w = 1 + 3 * Math.random() << 0;
html += temp.replace(/\{width\}/g, w*150).replace("{index}", i + 1).replace("{link}",i + 1);
}
$("#freewall").html(html);
var wall = new Freewall("#freewall");
wall.reset({
selector: '.brick',
animate: true,
cellW: 150,
cellH: 'auto',
onResize: function() {
wall.fitWidth();
}
});
var images = wall.container.find('.brick');
images.find('img').load(function() {
wall.fitWidth();
});
<div id="freewall" class="free-wall"></div>
You have to manually trigger the next element on click on the image. Just do something like below
A function to trigger featherlight to show next image. I had assumed you initialize featherlite using .brick a css selector. Feel free to change this to your desired one. This function builds your next a tags data-featherlight and calls featherlight over it.
function showNextImage(i) {
$('.brick a').featherlight('i/jpl/' + (((i +1) % (limitItem + 1))) + '.jpg');
}
Add a onclick in your div to call the function with current i.
var temp = "<div class='brick' style='width:{width}px;' onclick='showNextImage({index})'> <a href='#' data-featherlight='i/jpl/{link}.jpg'><img src='i/jpl/{index}.jpg' width='100%'></a></div>";
var w = 1, h = 1, html = '', limitItem = 54;
for (var i = 0; i < limitItem; ++i) {
w = 1 + 3 * Math.random() << 0;
html += temp.replace(/\{width\}/g, w*150).replace("/\{index\}/g", i + 1).replace("{link}",i + 1);
}
$("#freewall").html(html);

Fabricjs - How to detect canvas on mouse move?

In my fabricjs application, I had created dynamic canvases(variable's also dynamic). Here, I need to detect particular canvas while mouse move on canvas.
Sample code,
var i = 0, canvasArray = [];
$(this).find('canvas').each(function() {
i++;
var DynamicCanvas = 'canvas_'+i;
canvasArray[DynamicCanvas] = new fabric.Canvas('canvas_'+i,{
width : '200',
height : '200'
});
});
after this, I have 4 different canvases. Last added canvas has been activated. But i need to add object on any canvas.
So that i have to activate canvas using mouse move event. How can i achieve it.? Please help me on this.
Mullainathan,
Here some quick solution using jQuery:
var canvasStr = '';
var canvasArray = [];
var fabricCanvasArray = [];
var htmlStr = '';
var canvas = null;
//generate canavases
for (var i = 0; i < 4; i++){
canvasArray.push('c' + i);
htmlStr += '<canvas id="c' + i + '" width="200" height="200"></canvas>'
}
//append canvasses to the body
$('body').append(htmlStr);
//to the fabricjs parent div elements assign id's and generate string for jQuery with div id's
for (var i in canvasArray){
fabricCanvasArray[i] = new fabric.Canvas(canvasArray[i], {
isDrawingMode: true
});
$('#' + canvasArray[i]).parent().attr('id', ('div' + canvasArray[i]));
canvasStr += '#div' + canvasArray[i];
if (i < canvasArray.length - 1){
canvasStr += ',';
}
}
//jQuery event for mouse over each div element of the fabric canvas
$(canvasStr).mouseover(function(){
for (var i in fabricCanvasArray){
if (fabricCanvasArray[i].lowerCanvasEl.id == $(this).children(':first').attr('id')){
canvas = fabricCanvasArray[i];
canvas.freeDrawingBrush.width = 10;
var r = 255 - i*50;
var g = i * 50;
var b = 200 - i * 40;
canvas.freeDrawingBrush.color = 'rgb(' + r + ',' + g + ',' + b + ')';
canvas.on('mouse:up', function() {
//do your stuff
// canvas.renderAll();
});
break;
}
}
});
Also, you can run fiddle

rotate on mouse hover

I have this function but there are two issues I can't solve, first one is that the mouse action is set on all the screen and I want it to be when hover over the dive "ehab" only, not when I move mouse over screen,
the other issue is that when I have more than one div , the function works only on the first one ...
kindly advise me
/*
By : Ofelquis
Twitter: #felquis
Blog : tutsmais.com.br
Simples implementação ;)
*/
!(function ($doc, $win) {
var screenWidth = $win.screen.width / 2,
screenHeight = $win.screen.height / 2,
$ehab = $doc.querySelectorAll('#ehab')[0],
validPropertyPrefix = '',
otherProperty = 'perspective(600px)';
if(typeof $ehab.style.webkitTransform == 'string') {
validPropertyPrefix = 'webkitTransform';
} else {
if (typeof $ehab.style.MozTransform == 'string') {
validPropertyPrefix = 'MozTransform';
}
}
$doc.addEventListener('mousemove', function (e) {
// vars
var centroX = e.clientX - screenWidth,
centroY = screenHeight - (e.clientY + 13),
degX = centroX * 0.1,
degY = centroY * 0.1
// Seta o rotate do elemento
$ehab.style[validPropertyPrefix] = otherProperty + 'rotateY('+ degX +'deg) rotateX('+ degY +'deg)';
});
})(document, window);
The first problem, (I want it to be when hover the div "#ehab"), you need the attach the mousemove event to your div:
$ehab.addEventListener('mousemove', function (e) {
//You code here.
});
The second problem, (when I have more than one div , the function works only on the first one), you can't have duplicated IDs on your DOM tree, change the selector to a class, for example, .ehab then you have to loop through the matched elements, please try this code:
/*
By : Ofelquis
Twitter: #felquis
Blog : tutsmais.com.br
Simples implementação ;)
*/
!(function($doc, $win) {
var $ehabDIVs = $doc.querySelectorAll('.ehab'),
otherProperty = 'perspective(600px)';
for (var i = 0; i < $ehabDIVs.length; ++i) {
var $ehab = $ehabDIVs[i];
$ehab.addEventListener('mousemove', function(e) {
// vars
var centroX = (e.pageX - this.offsetLeft) - this.offsetWidth/2,
centroY = this.offsetHeight/2 - (e.pageY-this.offsetTop),
degX = centroX * 0.1,
degY = centroY * 0.1
if(this._leave) clearInterval(this._leave);
// Seta o rotate do elemento
this.style.transform = otherProperty + 'rotateY(' + degX + 'deg) rotateX(' + degY + 'deg)';
});
$ehab.addEventListener('mouseleave', function(e) {
var self = this;
this._leave = setTimeout(function() {
self.style.transform = 'rotateY(0deg) rotateX(0deg)';
}, 250);
});
}
})(document, window);
.ehab {
width:300px;
height:300px;
background-color:red;
margin:15px;
float:left;
transition: transform 0.15s ease;
}
<div class="ehab">First Div</div><div class="ehab">Second Div</div>
Good Luck Ismaiel.

How to make Coin Slider responsive?

After being created, the slider seems not to have a way to be resized, which is really bad for a responsive layout.
Is there a way to actually resize the Coin Slider plugin according to Twitter Bootstrap 3's media queries?
You might consider Coin Slider's demo as a fiddle.
Indeed, there is no way to resize it with the current plugin version. So, I wrote a script to resize the Coin Slider (you can test it on Coin Slider's demo site):
var resizeCoinSliderTo = function(coinSlider, toWidth, toHeight) {
var csColumns = 7;
var csRows = 5;
var imgWidth = toWidth;
var imgHeight = toHeight;
var cellWidth = imgWidth/csColumns;
var cellHeight = imgHeight/csRows;
var coinSliderId = coinSlider.attr("id");
coinSlider.css({
'width': imgWidth,
'height': imgHeight
});
$('.cs-'+coinSliderId).css({
'width': (cellWidth + 'px'),
'height': (cellHeight + 'px'),
'background-size': (imgWidth + 'px ' + imgHeight + 'px')
}).each(function() {
var cellOffsets = $(this).attr("id").replace("cs-"+coinSliderId,"");
var hOffSet = cellHeight * (Math.floor(parseInt(cellOffsets[0])-1) % csRows);
var wOffSet = cellWidth * (parseInt(cellOffsets[1])-1);
$(this).css({
"left": (wOffSet + 'px'),
"top": (hOffSet + 'px'),
"background-position": ((-wOffSet) + 'px ' + (-hOffSet) + 'px')
});
});
$('#cs-navigation-'+coinSliderId).children("a").css("top", (((imgHeight/2)-15)+'px'));
};
So, we just need to call the created resizeCoinSliderTo after each media queries breakpoints, handling the resize, without losing its ratio, to fit the screen properly:
<span id="mq-detector">
<span class="visible-xs"></span>
<span class="visible-sm"></span>
<span class="visible-md"></span>
<span class="visible-lg"></span>
</span>
#mq-detector {
visibility: hidden;
}
var coinSlider = $("#coin-slider");
var baseWidthDisplay = undefined;
var baseHeightDisplay = undefined;
var currentRatio = undefined;
var mqRatios = [0.75, 0.95, 0.8, 1];
var mqDetector = $("#mq-detector");
var mqSelectors = [
mqDetector.find(".visible-xs"),
mqDetector.find(".visible-sm"),
mqDetector.find(".visible-md"),
mqDetector.find(".visible-lg")
];
var checkCoinSliderForResize = function() {
for (var i = 0; i <= mqSelectors.length; i++) {
if (mqSelectors[i].is(":visible")) {
if (currentRatio == undefined) {
baseWidthDisplay = parseInt(coinSlider.css("width"));
baseHeightDisplay = parseInt(coinSlider.css("height"));
}
if (i == 0) {
var specialWidth = Math.floor(parseInt($("body").css("width"))*0.75);
if (specialWidth < 300){
specialWidth = 300;
}
var specialHeight = Math.floor(baseHeightDisplay * specialWidth / baseWidthDisplay);
resizeCoinSliderTo(coinSlider, specialWidth, specialHeight);
}
if (currentRatio != mqRatios[i]) {
currentRatio = mqRatios[i];
if (i > 0) {
resizeCoinSliderTo(coinSlider, baseWidthDisplay*currentRatio, baseHeightDisplay*currentRatio);
}
}
break;
}
}
};
$(window).on('resize', checkCoinSliderForResize);
checkCoinSliderForResize();
Make sure to place all JavaScript code after the DOM is ready, and after the coinslider was created.

How to add a new item to the end of the list using jQuery?

I have this function for adding a new item to the beginning of the list and removing the last one:
function addItem(id, text){
var el = $('#' + id);
var w = el.width();
el.css({
width: w,
overflow: 'hidden'
});
var ulPaddingLeft = parseInt(el.css('padding-left'));
var ulPaddingRight = parseInt(el.css('padding-right'));
el.prepend('<li>' + text + '</li>');
var first = $('li:first', el);
var last = $('li:last', el);
var fow = first.outerWidth();
var widthDiff = fow - last.outerWidth();
var oldMarginLeft = first.css('margin-Left');
first.css({
marginLeft: 0 - fow,
position: 'relative',
left: 0 - ulPaddingLeft
});
last.css('position', 'relative');
el.animate({ width: w + widthDiff }, 1500);
first.animate({ left: 0 }, 250, function() {
first.animate({ marginLeft: oldMarginLeft }, 1000, function() {
last.animate({ left: ulPaddingRight }, 250, function() {
last.remove();
el.css({
width: 'auto',
overflow: 'visible'
});
});
});
});
}
How can I make it work the other way around ? I want to add the item to the end and remove the first and also make it slide the other way around, like right to left.
Take a look at jQuery.append (and jQuery.prepend for beginning of list)
Your code seems really complicated. Simplifying it a little bit might give you something like this:
$("#whateverList").addItem("awesome")
jQuery.fn.addItem = function(text) {
var $li = $("<li>").text(text)
$(this).find("li:first").remove()
$(this).append($li)
}
jQuery plugin syntax is super easy to understand
append() to go to the bottom
var declarations at the top
Good luck!

Categories

Resources