Why are these two jQuery functions both not firing on click? - javascript

Okay, I have two jQuery functions. One of them is a simple explode effect on a div. The other function enhances the explode effect by sending particles in a circle around the div. When I click on the div with both functions set, it will only fire the explode effect and not the function with the debris on my site.
Something Strange
In jsfiddle the debris is working and not the explode, but on my site the explode effect is working but not the debris.
Here is the jsfiddle example: jsfiddle.net/FYB98/3/
Note: I'm using the same jQuery version for both my site and the jsfiddle example, that's jquery-1.9.1.
This is my code
<style>
.debris {
display: none;
position: absolute;
width: 28px;
height: 28px;
background-color: #ff00ff;
opacity: 1.0;
overflow: hidden;
border-radius: 8px;
}
#bubble {
position:absolute;
background-color: #ff0000;
left:150px;
top:150px;
width:32px;
height:32px;
border-radius: 8px;
z-index: 9;
}
</style>
<div id="content">
<div id="bubble"></div>
<div id="dummy_debris" class="debris" />
</div>
<script>
// jQuery bubble pop animation
// Ben Ridout (c) 2013 - http://BenRidout.com/?q=bubblepop
// You're free to use this code with above attribution (in source is fine).
$(function(){
// Document is ready
$("#bubble").on("click", function(e) {
pop(e.pageX, e.pageY, 13);
});
});
$( "#bubble" ).click(function() {
$( this ).toggle( "explode", {pieces: 50 }, 2000);
});
function r2d(x) {
return x / (Math.PI / 180);
}
function d2r(x) {
return x * (Math.PI / 180);
}
function pop(start_x, start_y, particle_count) {
arr = [];
angle = 0;
particles = [];
offset_x = $("#dummy_debris").width() / 2;
offset_y = $("#dummy_debris").height() / 2;
for (i = 0; i < particle_count; i++) {
rad = d2r(angle);
x = Math.cos(rad)*(80+Math.random()*20);
y = Math.sin(rad)*(80+Math.random()*20);
arr.push([start_x + x, start_y + y]);
z = $('<div class="debris" />');
z.css({
"left": start_x - offset_x,
"top": start_y - offset_x
}).appendTo($("#content"));
particles.push(z);
angle += 360/particle_count;
}
$.each(particles, function(i, v){
$(v).show();
$(v).animate(
{
top: arr[i][1],
left: arr[i][0],
width: 4,
height: 4,
opacity: 0
}, 600, function(){$(v).remove()
});
});
}
</script>

From your fiddle, it seems you missed to include jQuery UI.
Check this fiddle

You haven't put second click event in $(function) handler. Put both events in $(function) handler
$(function(){
// Document is ready
$("#bubble").on("click", function(e) {
pop(e.pageX, e.pageY, 13);
});
$( "#bubble" ).click(function() {
$( this ).toggle( "explode", {pieces: 50 }, 2000);
});
});
working demo : http://jsfiddle.net/FYB98/9/

Related

Make simple js fiddle animation start on button click instead of page load.

I found this rather cool Js fiddle and have been editing the animation a bit and think its something I can use on a current project. However im not the best with Javascript. All I really need to know to accomplish the rest of my goal is how to make the animation not start until you click a button.
Here is the animation for the js fiddle.
http://jsfiddle.net/apipkin/qUTwQ/
Here is the css.
#o {
width: 200px;
height: 400px;
position: relative;
border-bottom: 1px solid blue;}
.bubble {
border: 1px solid
#f40009; display: block;
position: absolute;
border-radius: 20px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
}
The rest is in the JS fiddle.
Thanks fo any help!
You can simply wrap it in a function and call that function on click.
DEMO
Create a button:
<button id="btn">Click</button>
And this js:
document.getElementById('btn').addEventListener('click', startAnimation);
function startAnimation() {
YUI().use('node', 'anim', 'anim-node-plugin', function(Y) {
var o = Y.one('#o'),
oW = o.get('offsetWidth'),
oH = o.get('offsetHeight'),
max = 12,
min = 4,
bubbles = 20,
timerDelay = 4000;
function makeBubble() {
var b = Y.Node.create('<span class="bubble"></span>');
b.plug(Y.Plugin.NodeFX, {
duration: 7,
easing: Y.Easing.easeOut,
to: {
top: 0,
opacity: 0
},
on: {
end: function() {
Y.later(10000, this, function(){
animBubble(this.get('node'));
});
}
}
});
o.append(b);
animBubble(b);
}
function animBubble(b) {
var v = Math.floor(Math.random() * (max - min)) + min;
b.setStyles({
height: v + 'px',
width: v + 'px',
borderRadius: v + 'px',
top: (oH + 2) + 'px',
opacity: 1
});
b.setStyle('left', Math.floor(Math.random() * (oW - v)));
b.fx.set('duration', Math.floor(Math.random() * 2 + 3));
b.fx.set('to.top', Math.floor(Math.random() * (oH / 2)));
b.fx.run();
}
for (i = 0; i < bubbles; i++) {
Y.later(Math.random() * timerDelay, this, function() {
makeBubble();
});
}
});
}

Simple range /value Slider in JavaScript

I am trying to do a simple Range/Value Slider by using javascript or jQuery, A button in a div.This slider should be done without bootstrapor any other pluginor with inbuild functions
My question is how to move the slider button within the div element and what mouse events are needed to do this?
Note:This is not a slideshow slider or image slider
Take a look at this simple slider implementation. Feel free to use and modify the way you prefer:
document.addEventListener('DOMContentLoaded', function() {
var sliders = document.querySelectorAll('.my-slider');
[].forEach.call(sliders, function(el, i) {
var btn = el.firstElementChild,
span = el.nextElementSibling.querySelector('span'),
isMoving = false;
var move = function(e) {
if (isMoving) {
var min = 0,
max = el.offsetWidth - btn.offsetWidth,
mousePos = (e.pageX - el.offsetLeft - (btn.offsetWidth / 2)),
position = (mousePos > max ? max : mousePos < min ? min : mousePos),
value = Math.floor((position / max) * 100);
btn.style.marginLeft = position + 'px';
btn.value = value;
span.textContent = value;
}
};
el.addEventListener('mousedown', function(e) {
isMoving = true;
move(e);
});
document.addEventListener('mouseup', function(e) {
isMoving = false;
});
document.addEventListener('mousemove', function(e) {
move(e);
});
});
});
.my-slider {
width: 250px;
border: 1px solid #999;
border-radius: 3px;
background-color: #ccc;
height: 10px;
line-height: 10px;
}
.my-slider__button {
border: 1px solid #333;
border-radius: 3px;
margin-top: -4px;
width: 18px;
height: 18px;
background-color: #eee;
display: block;
}
div {
margin-top: 6px;
}
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
You use drag and drop events, with a property setting that is restricted to the div it is within. Check out this link Drag Drop Reference Guide, and you will see everything you need. When you use draggable and dropable, you can restrict the movement to horizontal, and also set the element that it is bound to. This will allow you to only move left to right, and restrict vertical movement, and keep in the boundaries of the div. The same features bootstrap uses to get it done.
Here is a basic example showing some of the stuff mentioned:
$('. draggable').draggable({
axis: 'y',
handle: '.top'
drag: function( event, ui ) {
var distance = ui.originalPosition.top - ui.position.top;
// if dragged towards top
if (distance > 0) {
//then set it to its initial state
$('.draggable').css({top: ui.originalPosition.top + 'px'});
}
}
});
try this :
$('img').mouseenter(function(){ //or you can use hover()
// Set the effect type
var effect = 'slide';
// Set the options for the effect type chosen
var options = { direction: "right" };
// Set the duration (default: 400 milliseconds)
var duration = 1000;
$(this).toggle(effect, options, duration);
});

How to use % instead of px with draggable element?

I'm stucked and I need help. I'm making map with markers. I can add markers etc.
My main container have 100% width and height. When I click somewhere my marker has % values for example top: 34%; left: 35%;
After dragging marker new position have px value. I want to save % values.
Any ideas?
map.js
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
// $(maps).append('<div class="marker"></div>');
var marker = $('<div class="marker ui-widget-content"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker)
$('.marker').draggable().resizable();
}
map.click(function (e) {
// var x = e.pageX - this.offsetLeft;
// var y = e.pageY - this.offsetTop;
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
// $(this).append('<div class="marker"></div>');
AddPoint(x, y, this);
});
// drag function
$(".ui-widget-content").draggable({
drag: function( event, ui ) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
}
});
});
style.css
.wrapper {
margin: 0 auto;
width: 100%;
min-height: 400px;
overflow: hidden;
}
.map {
width: 100%;
position: relative;
}
.map > img {
max-width: 100%;
max-height: 100%;
}
.marker {
width: 10px;
height: 10px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
position: absolute;
left: 50%;
top: 50%;
z-index: 999;
}
#mapa {
width: 30px;
height: 30px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
z-index: 999;
}
some html code
<div class="wrapper">
<div class="map">
<img src="http://i.imgur.com/HtxXGR5.jpg" width="100%" height="auto" margin="15px 0;" alt="">
</div>
<button id="remove">Remove all markers</button>
</div>
If you want to capture the position, after the drag is ended (fire 1 time per drag) you can do this:
$('.marker').draggable({
stop: function() {
var offset = $(this).offset();
var mapOffest = $('.map').offset();
var x = ((offset.left - mapOffest.left)/ ($(".map").width() / 100))+"%";
var y = ((offset.top - mapOffest.top)/ ($(".map").height() / 100))+"%";
// We need to do something with thoses vals uh?
$(this).css('left', x);
$(this).css('top', y);
// or
console.log('X:'+x + '||Y:'+y);
}
});
Fiddle here
Take note that the event has been set on the marker directy, this was probably your mistake.
The little calcul needs to take care of the map offset, which you don't need if your map is a full width/height (window size)
If you need, or prefer use the drag event rather than the stop, theses lines won't have any effects
$(this).css('left', x);
$(this).css('top', y);
But you'll still be able to capture the position, the console values will be goods.
Hope it may helps you.
problem solved, DFayet thank's again
final code
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
var marker = $('<div class="marker"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker);
$('.marker').draggable({
stop: function(event, ui) {
var thisNew = $(this);
var x = (ui.position.left / thisNew.parent().width()) * 100 + '%';
var y = (ui.position.top / thisNew.parent().height()) * 100 + '%';
thisNew.css('left', x);
thisNew.css('top', y);
console.log(x, y);
}
});
}
map.click(function (e) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
AddPoint(x, y, this);
});
});

How to transfer events into the canvas { pointer-events : none }; (!in KonvaJS)

The essence of the title is described and presented in my example.
My task is to make the pseudo shape. You need to hover on the canvas element (triangle), canvas accepted property {pointer-events:all}, and the care with this element {pointer-events:none}. How this can be done using the framework konvajs.
/*NON GIST*/
var stage=new Konva.Stage({container:'container',width:300,height:300})
,layer=new Konva.Layer()
,triangle=new Konva.RegularPolygon({x:80,y:120,sides:3,radius:80,fill:'#00D2FF',stroke:'black',strokeWidth:4})
,text=new Konva.Text({x:10,y:10,fontFamily:'Calibri',fontSize:24,text:'',fill:'black'});
function writeMessage(message){text.setText(message);layer.draw();}
/*GIST*/
triangle.on('mouseout', function() {
$('#container').css('pointer-events',/*!*/'none');
writeMessage('Mouseout triangle');
});
/*! How do I know if the events are not tracked on the canvas?*/
triangle.on('mousemove', function() {
$('#container').css('pointer-events',/*!*/'all');
var mousePos = stage.getPointerPosition();
var x = mousePos.x - 190;
var y = mousePos.y - 40;
writeMessage('x: ' + x + ', y: ' + y);
});
/*/GIST/*/
layer.add(triangle);
layer.add(text);
stage.add(layer);
body{
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;}
#container{
position:absolute;
z-index:1;
}
.lower-dom-element{
position:absolute;
z-index:0;
padding:20px;
background:#0e0;
top: 90px;
left: 0px;}
<script src="https://cdn.rawgit.com/konvajs/konva/0.9.0/konva.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="container"></div>
<div class="lower-dom-element">
If the POINTER-EVENTS on me, then canvas POINTER-EVENTS:NONE, and vice versa.
If the events are not on the triangle, then the event with me.
</div>
PS: sorry for my english.
var $con = $('#container');
$(document.body).mousemove(function(event) {
var x = event.clientX, y = event.clientY;
var offset = $con.offset();
// manually check intersection
if (layer.getIntersection({x: x - offset.left, y: y - offset.top})){
$con.css('pointer-events',/*!*/'all');
} else {
$con.css('pointer-events',/*!*/'none');
}
});
Demo: http://jsfiddle.net/vfp22dye/3/

Hook jQuery validation message changes

I want to display my jQuery validation messages in a tooltip. In order to accomplish this, I started out by adding the following CSS rules to my stylesheet:
fieldset .field-validation-error {
display: none;
}
fieldset .field-validation-error.tooltip-icon {
background-image: url('/content/images/icons.png');
background-position: -32px -192px;
width: 16px;
height: 16px;
display: inline-block;
}
and a very small piece of JS code:
; (function ($) {
$(function() {
var fields = $("fieldset .field-validation-valid, fieldset .field-validation-error");
fields.each(function() {
var self = $(this);
self.addClass("tooltip-icon");
self.attr("rel", "tooltip");
self.attr("title", self.text());
self.text("");
self.tooltip();
});
});
})(jQuery);
The issue is that I now need to capture any event when the validation message changes, I've been looking at the source for jquery.validate.unobtrusive.js, and the method I'd need to hook to is the function onError(error, inputElement) method.
My tooltip plugin works as long as I've an updated title attribute, the issue comes when the field is revalidated, and the validation message is regenerated, I would need to hook into that and prevent the message from being put out there and place it in the title attribute instead.
I want to figure out a way to do this without modifying the actual jquery.validate.unobtrusive.js file.
On a second note, how could I improve this in order to leave the functionality unaltered in case javascript is disabled?
Ok I went with this, just in case anyone runs into this again:
; (function ($) {
$(function() {
function convertValidationMessagesToTooltips(form) {
var fields = $("fieldset .field-validation-valid, fieldset .field-validation-error", form);
fields.each(function() {
var self = $(this);
self.addClass("tooltip-icon");
self.attr("rel", "tooltip");
self.attr("title", self.text());
var span = self.find("span");
if (span.length) {
span.text("");
} else {
self.text("");
}
self.tooltip();
});
}
$("form").each(function() {
var form = $(this);
var settings = form.data("validator").settings;
var old_error_placement = settings.errorPlacement;
var new_error_placement = function() {
old_error_placement.apply(settings, arguments);
convertValidationMessagesToTooltips(form);
};
settings.errorPlacement = new_error_placement;
convertValidationMessagesToTooltips(form); // initialize in case of model-drawn validation messages at page render time.
});
});
})(jQuery);
and styles:
fieldset .field-validation-error { /* noscript */
display: block;
margin-bottom: 20px;
}
fieldset .field-validation-error.tooltip-icon { /* javascript enabled */
display: inline-block;
margin-bottom: 0px;
background-image: url('/content/images/icons.png');
background-position: -32px -192px;
width: 16px;
height: 16px;
vertical-align: middle;
}
I'll just include the tooltip script I have, since it's kind of custom-made (though I based it off someone else's).
; (function ($, window) {
$.fn.tooltip = function (){
var classes = {
tooltip: "tooltip",
top: "tooltip-top",
left: "tooltip-left",
right: "tooltip-right"
};
function init(self, tooltip) {
if ($(window).width() < tooltip.outerWidth() * 1.5) {
tooltip.css("max-width", $(window).width() / 2);
} else {
tooltip.css("max-width", 340);
}
var pos = {
x: self.offset().left + (self.outerWidth() / 2) - (tooltip.outerWidth() / 2),
y: self.offset().top - tooltip.outerHeight() - 20
};
if (pos.x < 0) {
pos.x = self.offset().left + self.outerWidth() / 2 - 20;
tooltip.addClass(classes.left);
} else {
tooltip.removeClass(classes.left);
}
if (pos.x + tooltip.outerWidth() > $(window).width()) {
pos.x = self.offset().left - tooltip.outerWidth() + self.outerWidth() / 2 + 20;
tooltip.addClass(classes.right);
} else {
tooltip.removeClass(classes.right);
}
if (pos.y < 0) {
pos.y = self.offset().top + self.outerHeight();
tooltip.addClass(classes.top);
} else {
tooltip.removeClass(classes.top);
}
tooltip.css({
left: pos.x,
top: pos.y
}).animate({
top: "+=10",
opacity: 1
}, 50);
};
function activate() {
var self = $(this);
var message = self.attr("title");
var tooltip = $("<div class='{0}'></div>".format(classes.tooltip));
if (!message) {
return;
}
self.removeAttr("title");
tooltip.css("opacity", 0).html(message).appendTo("body");
var reload = function() { // respec tooltip's size and position.
init(self, tooltip);
};
reload();
$(window).resize(reload);
var remove = function () {
tooltip.animate({
top: "-=10",
opacity: 0
}, 50, function() {
$(this).remove();
});
self.attr("title", message);
};
self.bind("mouseleave", remove);
tooltip.bind("click", remove);
};
return this.each(function () {
var self = $(this);
self.bind("mouseenter", activate);
});
};
$.tooltip = function() {
return $("[rel~=tooltip]").tooltip();
};
})(jQuery, window);

Categories