javascript raphael object function passing - javascript

I apologize for asking this question but I am just looking for a little guidance on this morning. I simply want to create a function so that way I can make a Raphael element glow by just passing in that element. Below is the code I have. Why does this not work?
var paper = Raphael("playarea", 500, 500);
var rectangle = paper.rect(100, 100, 200, 200, 4);
function elemHover(var el)
{
el.hover(
// When the mouse comes over the object //
// Stock the created "glow" object in myCircle.g
function() {
this.g = this.glow({
color: "#0000EE",
width: 10,
opacity: 0.8
});
},
// When the mouse goes away //
// this.g was already created. Destroy it!
function() {
this.g.remove();
});
}
elemHover(rectangle);
here is the fiddle http://jsfiddle.net/aZG6C/15/

You should fill the element( rectangle in our case) to trigger the hover.
rectangle.attr("fill", "red");
Try this fiddle http://jsfiddle.net/aZG6C/17/
The full code will look like
<div id="playarea"></div>
​<script type="text/javascript">
var paper = Raphael("playarea", 500, 500);
var rectangle = paper.rect(100, 100, 200, 200, 4);
function elemHover(el)
{
el.hover(
// When the mouse comes over the object //
// Stock the created "glow" object in myCircle.g
function() {
this.g = this.glow({
color: "#0000EE",
width: 10,
opacity: 0.8
});
},
// When the mouse goes away //
// this.g was already created. Destroy it!
function() {
this.g.remove();
});
}
rectangle.attr("fill", "red");
elemHover(rectangle);
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Update
Hover event is triggered only if the element is filled with something. If you want to have a transparent element you can try
rectangle.attr("fill", "transparent");
Check the fiddle here http://jsfiddle.net/aZG6C/20/

Related

How to group DOM elements and their methods in p5.js?

I had made a menu for a game in p5.js and I wanted the menu to be simple but well presented and very interactive. Also, I wanted to have a small piece of code. I have achieved the first conditions but I still think my code is very big.
I encourage you to please change/edit/delete my code and write the same idea in a better way
let modes = [];
var mode1, mode2, mode3, mode4;
function setup() {
createCanvas(400, 500);
mode1 = createP("Mode 1");
mode2 = createP("Mode 2");
mode3 = createP("Mode 3");
mode4 = createP("Mode 4");
mode1.class("mode");
mode2.class("mode");
mode3.class("mode");
mode4.class("mode");
modes = selectAll(".mode");
for (var i = 0; i < modes.length; i++) {
modes[i].style("font-size", "50px");
}
mode1.position(40, 115);
mode2.position(215, 115);
mode3.position(40, 300);
mode4.position(215, 300);
}
function draw() {
background("#befecd");
noFill();
strokeWeight(8);
rect(20, 100, 360, 360);
line(20, 280, 380, 280);
line(200, 100, 200, 460);
fill(0);
textSize(64);
text("MENU", 100, 70);
mode1.mouseOver(function () {
mode1.html("Mode 1<br>description");
mode1.style("font-size", "35px");
});
mode2.mouseOver(function () {
mode2.html("Mode 2<br>description");
mode2.style("font-size", "35px");
});
mode3.mouseOver(function () {
mode3.html("Mode 3<br>description");
mode3.style("font-size", "35px");
});
mode4.mouseOver(function () {
mode4.html("Mode 4<br>description");
mode4.style("font-size", "35px");
});
mode1.mouseOut(function () {
mode1.html("Mode 1");
mode1.style("font-size", "35px");
});
mode2.mouseOut(function () {
mode2.html("Mode 2");
mode2.style("font-size", "50px");
});
mode3.mouseOut(function () {
mode3.html("Mode 3");
mode3.style("font-size", "50px");
});
mode4.mouseOut(function () {
mode4.html("Mode 4");
mode4.style("font-size", "50px");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.min.js"></script>
This are some ideas I have thought about:
Making that elements on the HTML page
Keep the different properties on variable variables and have only one mouseOver() / mouseOut() function for all the DOM elements
As you can see, I have gotten all elements on another variable, but I haven’t used that. Shall I?
Change to another programming language. I don’t feel very confortable with p5.js sometimes when I do games or those types of things. I ask you for other programming languages (not the best or personal opinion, I only want to know other options)
The solution to the thing1, thing2, thing3... thingN in pretty much all languages is arrays and iteration (usually loops in imperative languages).
You can factor out the variable parts of each repeated chunk of logic and generalize to structure that represents the raw data, then loop over it and build your elements from those variables.
const modeData = [
{description: "foo foo foo", position: [40, 115]},
{description: "bar bar bar", position: [215, 115]},
{description: "baz baz baz", position: [40, 300]},
{description: "quux quux", position: [215, 300]},
];
const modes = [];
function setup() {
createCanvas(400, 500);
modeData.forEach(({description, position: [x, y]}, i) => {
const p = createP(`Mode ${i + 1}`);
modes.push(p);
p.class("mode");
p.style("font-size", "45px");
p.position(x, y);
p.mouseOver(() => {
p.html(`Mode ${i + 1}<br>${description}`);
p.style("font-size", "35px");
});
p.mouseOut(() => {
p.html(`Mode ${i + 1}`);
p.style("font-size", "50px");
});
});
}
function draw() {
background("#befecd");
noFill();
strokeWeight(8);
rect(20, 100, 360, 360);
line(20, 280, 380, 280);
line(200, 100, 200, 460);
fill(0);
textSize(64);
text("MENU", 100, 70);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script>
As you can see, the mouse over/out listeners shouldn't be re-added on every frame in draw, only one time in setup.
As a UI/UX/app design aside, it's a bit odd to combine canvas drawing and DOM elements like this, especially when resizing is involved. You can see some odd flashing between mouseover/out at certain mouse positions when the description text is small. I'd likely use CSS-styled DOM <div> elements rather than canvas lines to create the boxes. If the text content is larger, the problem disappears, but the point stands since there are other layout issues that can occur. Your use case may be an exception, so this is just a rule of thumb.
Note also that you start at 45px, then return to 50px after mouseout. Maybe those two numbers should be the same.

How to modify TimelineLite timing?

I’m quite new with the GreenSock and I got myself in trouble...
I would like to modify GreenSock TimelineLite timing offset for reverse so that some delays get deleted (I think that they are called staggers).
Here is an example: http://jsfiddle.net/4bvnv1d5/
var red = $('.red');
var green = $('.green');
var blue = $('.blue');
var black = $('.black');
var tl = new TimelineLite({onReverseComplete:reverseCompleted});
$('#start').click(function(){
tl.to(red, 0.3, {ease: Power1.easeInOut, 'margin-left':'100px'});
tl.to(green, 0.3, {ease: Power1.easeInOut, 'margin-left':'100px'});
tl.to(blue, 0.3, {ease: Power1.easeInOut, 'margin-left':'100px'});
tl.to(black, 0.3, {ease: Power1.easeInOut, 'margin-left':'100px', onComplete:lastCompleted, onCompleteParams:[black]}, "+=4");
});
$('#reverse').click(function(){
tl.reverse();
});
function lastCompleted(target) {
console.log('lastCompleted');
}
function reverseCompleted(){
console.log('reverseCompleted');
tl.clear();
tl.restart();
}
On play there is a four second delay with the last box, but on the reverse I’d like to animations to play right after each other with no delays. There is function lastCompleted() which is triggered after the last tween gets run. How can I use that function to remove the delay between the black and blue box animations?
Thanks!
Take a look at this fiddle.
JavaScript:
var red = $('.red');
var green = $('.green');
var blue = $('.blue');
var black = $('.black');
var tl = new TimelineLite({
paused: true,
callbackScope: this,
onReverseComplete: onTlReverseComplete
});
tl.staggerTo([red, green, blue], 0.3, { marginLeft: 100, ease: Power1.easeInOut }, 0.3);
tl.addLabel('MyLabel');
tl.to(black, 0.3, { marginLeft: 100, ease: Power1.easeInOut, onReverseComplete: onBlackBoxReverseComplete, callbackScope: this }, '+=4');
$('#start').click(function () {
tl.play();
});
$('#reverse').click(function () {
tl.reverse();
});
function onBlackBoxReverseComplete() {
tl.reverse('MyLabel');
}
function onTlReverseComplete() {
tl.stop();
}
Quite a few things have changed from your code. Here is the list:
The tweens are added into the tl instance outside the scope of click handler of #start button. The click handler only .play()s the timeline forward.
.staggerTo() method is used instead of adding adding the 3 tweens one by one before the one for .black element.
Also, margin-left has been replaced by its JS equivalent marginLeft and since it accepts numbers and defaults to pixels, no need to pass the values as strings.
The tween for .black element has now a onReverseComplete callback.
Hope this helps. Let me know if you have any questions.

spinner on form submit

I’m looking to build a script thats open a spinner on form submit or select change.
I’d like to use spin.js, (this is a working example from the developer):
var opts = {
lines: 11, // The number of lines to draw
length: 15, // The length of each line
width: 10, // The line thickness
radius: 30, // The radius of the inner circle
corners: 1, // Corner roundness (0..1)
rotate: 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color: '#000', // #rgb or #rrggbb
speed: 0.6, // Rounds per second
trail: 60, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
var spinner = null;
var spinner_div = 0;
$(document).ready(function() {
spinner_div = $('#spinner').get(0);
$("#btn-spin").click(function(e) {
e.preventDefault();
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
} else {
spinner.spin(spinner_div);
}
});
});
so.. when i click on my submit button
<input id="btn-spin" type="submit" name="next" value="Continua" class="button-big"/>
or when i change a value on my select
<select name="billing_country" onChange="this.form.submit();">
{billing_country_options}
</select>
I’d like to:
add “lightbox-is-open” and “lightbox-is-fixed” classes to HTML
remove “hidden” class from my glasspane div
start (or show) the spinner
wait 500ms
submit the button or the select (and then other page will be loaded)
someone can help me please?
it’s too hard, a very difficult puzzle for me, (i’m a sound engineer, not a web developer)
thanks so much
Assuming that you have initialized your spinner correctly, we can listen to either the form submit or select change events using jQuery, and avoid using inline JS. For your <select>, just remove the inline JS.
$(function() {
// Remember to use 'var'
var spinner_div = $('#spinner').get(0),
spinner,
opts = {
// Opts go here
},
showSpinner = function() {
// Add 'lightbox-is-open' and 'lightbox-is-fixed' classes to HTML
$('html').addClass('lightbox-is-open lightbox-is-fixed');
// Remove 'hidden' class from '.glasspane'
$('.glasspane').removeClass('hidden');
// Show spinner
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
} else {
spinner.spin(spinner_div);
}
// Submit form after 500ms
var timer = window.setTimeout(function() {
$('form').submit();
}, 500);
};
// Bind events
$('form').on('submit', function(e) {
e.preventDefault();
showSpinner();
});
$('#btn-spin').on('click', function(e) {
e.preventDefault();
showSpinner();
});
$('select').on('change', showSpinner);
});

How to prevent loss hover in Raphael?

I'm developing some page when I use Raphael liblary to draw some items.
my App
So my problem is in that when I'm moving to some rect it growing up but when my mouse is on text which is positioning on my rect, it loss his hover. You can see it on my app example.
var paper = new Raphael(document.getElementById('holder'), 500, object.length * 100);
drawLine(paper, aType.length, bType.length, cType.length, cellSize, padding);
process = function(i,label)
{
txt = paper.text(390,((i+1)* cellSize) - 10,label.devRepo)
.attr({ stroke: "none", opacity: 0, "font-size": 20});
var a = paper.rect(200, ((i+1)* cellSize) - 25, rectWidth, rectHeight)
.hover(function()
{
this.animate({ transform : "s2"}, 1000, "elastic");
this.prev.animate({opacity: 1}, 500, "elastic");
this.next.attr({"font-size" : 30});
},
function()
{
this.animate({ transform : "s1" }, 1000, "elastic");
this.prev.animate({opacity: 0}, 500);
this.next.attr({"font-size" : 15});
});
}
I have tried e.preventDefault(); on hover of this.next and some other solutions but it's doesn't work.
Any help would be appreciated.
Most people will suggest you place a transparent rectangle over the box and the labels and attach the hover functions to that instead. (If memory serves, you have to make the opacity 0.01 instead of 0 to prevent the object from losing its attached events.) This works fine, but I don't love this solution; it feels hacky and clutters the page with unnecessary objects.
Instead, I recommend this: Remove the second function from the hover, making it functionally a mouseover function only. Before you draw any of the rectangles and labels, make a rectangular "mat" the size of the paper. Then, attach the function that minimizes the label as a mouseover on the mat. In other words, you're changing the trigger from mousing out of the box to mousing over the area outside of it.
I left a tiny bit of opacity and color on the mat to be sure it's working. You can just change the color to your background color.
var mat = paper.rect(0, 0, paper.width, paper.height).attr({fill: "#F00", opacity: 0.1});
Now, you want to make a container for all the rectangles so you can loop through them to see which need to be minimized. I made an object called "rectangles" that contains the objects we're concerned with. Then:
mat.mouseover(function () {
for (var c = 0; c < rectangles.length; c += 1) {
//some measure to tell if rectangle is presently expanded
if (rectangles[c].next.attr("font-size")) {
rectangles[c].animate({
transform : "s1"
}, 1000, "elastic");
rectangles[c].prev.animate({opacity: 0}, 500);
rectangles[c].next.attr({"font-size" : 15});
}
}
});
Then I just removed the mouseout function from the individual rectangles.
jsBin
To be clear, this will have some downsides: If people run the mouse around really fast, they can expand several rectangles at the same time. This is remedied as soon as the mouse touches the mat. I think the functionality looks pretty nice. But the invisible mats is always an option.
I wrote a small extension to Raphael - called hoverInBounds - that resolves this limitation.
Demo: http://jsfiddle.net/amustill/Bh276/1
Raphael.el.hoverInBounds = function(inFunc, outFunc) {
var inBounds = false;
// Mouseover function. Only execute if `inBounds` is false.
this.mouseover(function() {
if (!inBounds) {
inBounds = true;
inFunc.call(this);
}
});
// Mouseout function
this.mouseout(function(e) {
var x = e.offsetX || e.clientX,
y = e.offsetY || e.clientY;
// Return `false` if we're still inside the element's bounds
if (this.isPointInside(x, y)) return false;
inBounds = false;
outFunc.call(this);
});
return this;
}

Stop animation and reset position of an element in Raphaël.js

I have this simple animation that moves from side to side, Im trying to create a reset button so that the animation stops and gets back to default, but I cant seem to get i right.
The library I am using is Raphael, but I'm almost sure that with a simple javascript I can reset the values inside the function.
Body onload init function
function init() {
paper = Raphael("loadSVG");
var bg = paper.rect( 0, 0, "240px", "90px", 0 );
bg.attr( {fill: "#f3f3ff"} );
rect1 = paper.rect(150, 20, 50, 50);
rect1.attr( {fill: "#ffaaaa", "stroke-width": 3} );
}
The animation function
function moveRect1() {
if( xEnd == 150 )
xEnd = 50;
else
xEnd = 150;
rect1.animate( {x: xEnd}, 1000, "Sine", function (){
moveRect1();
});
}
and the stop button that don't work :)
function stopsvgRect1() {
rect1.stop();
}
You need to bind the stop button to the function you've created.
For example like this:
document.querySelector('#stop').onclick = function() {
stopsvgRect1();
};
Open this fiddle to see it in action.
edit:
As the position should also be resetted, you can choose Raphael.transform() for this action.
Open my updated fiddle to see how it works.

Categories