How do I use jQuery code through a Drupal 8 module? - javascript

How do I use jQuery through a Drupal 8 module?
I'm trying to get some jquery code running on a drupal 8 website. It's a div animation that randomly moves the div within a wrapper.
I've added the JS and CSS files and they're both showing in the source. I've then added the Div ID of 'container' to html.html.twig(yes I copied it into my theme folder first) -
{%
set body_classes = [
logged_in ? 'user-logged-in',
not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
node_type ? 'page-node-type-' ~ node_type|clean_class,
db_offline ? 'db-offline',
theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position,
theme.has_glyphicons ? 'has-glyphicons',
'container',
]
%}
Also added a div to use for this. Again in html.html.twig
<js-bottom-placeholder token="{{ placeholder_token|raw }}"> //**Not part of my code just adding it for comparison.
<div class='fly'>TEST DIV, IF I MOVE I'M WORKING!</div>
So the files show up in the source and the source also shows that the div ID of container has been added.
Here's the jQuery code, keep in mind that I've adjusted it to work with Drupal 8 so there's probably a syntax error or two.
$.extend(Drupal.theme, {
animateDiv: (function() {
($('.fly')); }),
* Almost certain the problem is here ^^^
makeNewPosition: function ($container) {
// Get viewport dimensions (remove the dimension of the div)
var h = $container.height() - 10;
var w = $container.width() - 10;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
},
animateDiv: function ($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$target.animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv($target);
});
},
calcSpeed: function (prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.23;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
});
Here's the CSS code
.fly {
width: 50px;
height:50px;
background-color: red;
position:fixed;
}
That's what I've tried and yet there's still no jQuery activity, I've also tried using different types for class names(.div instead of #div etc) which I think is where the problem is. The flying div shows but isn't being styled and there's no jQuery. What am I doing wrong?
Update: After playing with the code for awhile I've managed to at least get the style to show on the div. jQuery still a no show though..

Got the answer here https://drupal.stackexchange.com/questions/214483/how-do-i-use-jquery-code-through-a-module-theme/214485?noredirect=1#comment262213_214485
Apparently my Drupal/jQuery syntax wasn't correct.

Related

Element not staying within defined area in javascript

I wrote a basic program that moves a button inside a DIV element. The button is not staying within the area I had intended. On the HTML side I have code that defines the DIV with an id = "page". Here is the js code. Why is the button not staying within the DIV element?
var buttonState = document.getElementById("clickMe");
var maxWidth = document.getElementById("page");
var maxHeight = document.getElementById("page");
var pageWidth = maxWidth.clientWidth;
var pageHeight = maxHeight.clientHeight;
var screenWidth = 0;
var screenHeight = 0;
function moveButton() {
"use strict";
// Find max width and height of screen and set variables to random number within parameters
screenWidth = Math.floor(Math.random() * (pageWidth)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight)) + 1;
console.log(screenWidth);
console.log(screenHeight);
// Button position
buttonState.style.left = (screenWidth) + "px";
buttonState.style.top = (screenHeight) + "px";
// Button size
buttonState.style.width = buttonSize + "em";
buttonState.style.height = buttonSize + "em";
In your equations for screenWidth and screenHeight you need to take into account the size of the button.
The div is positioned based on the top left pixel so if you end up with Math.random() returning 1 or something very close to it, the button will fall out of the page unless you subtract the button sizes from the maxes.
var buttonWidthPx = buttonState.offsetWidth;
var buttonHeightPx = buttonState.offsetHeight;
screenWidth = Math.floor(Math.random() * (pageWidth - buttonWidthPx)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight - buttonHeightPx)) + 1;
Also make sure to set the positioning of the button to relative so it positions inside the div and not absolute to the document.
First thought, it is probably more of a css layout issue than javascript or html.
The first clue to this is
buttonState.style.left
buttonState.syyle.top
If you check the buttonState in Chrome DevTools you might find the layout to be: absolute and that would be one good reason why it does not layout as intended. Another would be if layout is set to static.
Here is a link that gives good depth of information on css layout settings: http://alistapart.com/article/css-positioning-101
The first thing I would try would be to open DevTools and deselect (remove) all the styles that buttonState has until you find the layout that is causing the problem.
I don't know the exact problem that you are facing because you didn't provide any HTML/CSS, but check out this fiddle for a working example.
<div id="page">
<button id="clickMe">Click Me</button>
</div>
<button id="move">Move Button</button>
#page {
width:300px;
height: 300px;
background-color: whitesmoke;
}
#clickMe {
position: relative;
top: 0;
left: 0;
}
var page = document.getElementById("page");
var pageWidth = page.clientWidth;
var pageHeight = page.clientHeight;
var button = document.getElementById("clickMe");
var buttonWidth = button.clientWidth;
var buttonHeight = button.clientHeight;
function moveButton() {
var x = Math.floor(Math.random() * (pageWidth - buttonWidth));
var y = Math.floor(Math.random() * (pageHeight - buttonHeight));
button.style.left = x + "px";
button.style.top = y + "px";
}
document.getElementById("move").onclick = moveButton;

Creating an effect wherever mouse goes

So I have been trying endlessly to try and do something similar too what this site is doing (http://whois.domaintools.com/). I'm trying to get a webpage, so wherever the mouse moves over the webpage, that kind of effect follows it (I'm sorry I don't know what I would call the effect).
I've read how to ask questions on here, but I don't know what too look for so it's difficult for me to attempt this. So far this link (http://p5js.org/learn/demos/Hello_P5_Drawing.php) I've used the code from this and played around with it but i'm just puzzled as too how I would go about doing this.
Thanks for any help, I've been banging my head against a brick wall for a good couple of days now.
This seems to be some kind of particle system. I would start the following way: First create a class for a particle, it should have a random x and y coordinate, and it should change it's postion periodically to a random new postion. Then create a lot of instances of the particle and distribute them over the page.
http://jsfiddle.net/aggoh0s1/3/
/* each particle will move in a 100px100px square */
var gutterWidth = 100;
/* class definition */
var Particle = function(x, y) {
var t = this;
t.x = x;
t.y = y;
t.elem = $('<div class="particle" />');
t.elem.css({ left: x+"px", top: y+"px"});
$('body').append(t.elem);
/* create a new position every 500-1000 milliseconds */
var milliSecs = 500 + Math.random() * 500;
t.ptinterval = setInterval(function() {
var dx = Math.round(Math.random() * gutterWidth);
var dy = Math.round(Math.random() * gutterWidth);
t.elem.animate({left: (t.x + dx)+"px", top: (t.y + dy) + "px"}, 600);
}, milliSecs);
};
/* create a 1000px1000px area where particles are placed each 100px */
var particles = [];
var newParticle;
for(var x = 0; x < 1000; x = x + gutterWidth) {
for(var y = 0; y < 1000; y = y + gutterWidth) {
newParticle = new Particle(x,y);
particles.push(newParticle);
}
}
CSS:
.particle {
width: 2px;
height: 2px;
background-color: black;
position: absolute;
}
Using this logic, you could also use a canvas to display the particles instead of a html div like it is done on whois.domaintools.com. The next step should be to connect the particles with lines to each other, and after that some code should hide all particles that are some distance away from the mouse position.
I've developed the following solution for the effect which you are referring. This is done using jQuery using the event mousemove(). Bind this event to your body where the content is.
Method :
Create an element with the following css on your body. You can create the element onthefly using jQuery as well.
<div class='hover'></div>
CSS
.hover{
position:absolute;
width:100px;
height:100px;
background-color:#fff;
}
The add the following code to your page.
$('body').mousemove(function(event){
$('.hover').css({
'top' : event.pageY,
'left': event.pageX
})
});
The above code will bind an event to your mouse move and I change the element position according to the mouse coordinates.
This fiddle shows a running example
I've given you the basic idea of the solution! You will have to medle with the css and jquery to add the looks and feels of the effect which you refer to.
See the simple example
<img id="imgMove" src="Images/img1.jpg" height="100" width="100" style="position: absolute;" />
JQuery
$(document).ready(function () {
$(document).mousemove(function (e) {
$("#imgMove").css({ "top": e.pageY - 50, "left": e.pageX - 50 }); // e.pageX - Half of Image height, width
})
})

Moving a box to a random position with angularjs

I am looking for a way to implement the exact functionality from this answer using angularjs: Specifically, for a box (div) to move randomly around a screen, while being animated. Currently I have tried
myApp.directive("ngSlider", function($window) {
return {
link: function(scope, element, attrs){
var animateDiv = function(newq) {
var oldRect = element.getBoundingClientRect();
var oldq = [oldRect.top, oldRect.left];
if (oldq != newq){
var dir = calcDir([oldq.top, oldq.left], newq);
element.moveTo(oldq.left + dir[0], oldq.top + dir[1]);
setTimeout(animateDiv(newq), 100);
}
};
var makeNewPosition = function() {
// Get viewport dimensions (remove the dimension of the div)
var window = angular.element($window);
var h = window.height() - 50;
var w = window.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
};
function calcDir(prev, next) {
var x = prev[1] - next[1];
var y = prev[0] - next[0];
var norm = Math.sqrt(x * x + y * y);
return [x/norm, y/norm];
}
var newq = makeNewPosition();
animateDiv(newq);
}
};
});
There appears to be quite a bit wrong with this, from an angular point of view. Any help is appreciated.
I like to take advantage of CSS in situations like this.
absolutely position your div
use ng-style to bind top and left attributes to some in-scope variable
randomly change the top and left attributes of this in-scope variable
use CSS transitions on top and left attributes to animate it for you
I made a plnkr! Visit Kentucky!

Temporarily replacing an image at a random, constantly shifting position

Building on my previous inquiries, I have an image, cat.jpg, that is being cloned, resized (halved, to be precise), then sent to a random position on the page via jQuery's .css() and .animate(). Now, when a cat is clicked, I'd like it to generate a new image/element in its place temporarily before removing it. So the order of events would be:
Click cat.
Cat explodes into 3 smaller kittens.
Clicked cat element is removed and a new image temporarily takes its place.
Cat replacement image is removed after set amount of time (say, one second).
Here's where I'm at thus far. Everything is up to snuff save for keeping the new kittens within the document boundaries (which I'll solve on my own) and the replacement image. Here's the Fiddle, and here's the code:
var explode;
$('img.cat').click(explode=function() {
var contW = $(document).width();
var contH = $(document).height();
for (var i = 1; i <= 3; i++){
var source = $(this).position();
var posNeg = Math.random() < 0.5 ? -1 : 1;
var newTop = Math.floor(Math.random() * (contH / 2 + (posNeg * $(this).height()))) * posNeg;
var posNeg = Math.random() < 0.5 ? -1 : 1;
var newLeft = Math.floor(Math.random() * (contW / 2 + (posNeg * $(this).width()))) * posNeg;
var $kitty = $(this).clone().css({
width: $(this).width() / 2,
height: $(this).height() / 2
});
$('#container').append($kitty);
$kitty.css({ top: source.top, left: source.left })
.animate({ top: newTop+'px', left: newLeft+'px' }, 300)
.click(explode);
}
$(this).remove();
});
I know I have to get the current position of the $kitty (or rather img.cat) being clicked on and set the new object to that via CSS, but my implementation is flawed.
var $lion = $('#replacement').clone().css({
top: newTop,
left: newLeft,
});
$('#container').append($lion);
<img id="replacement" src="http://images1.wikia.nocookie.net/__cb20130326142633/warriors/images/4/47/Lion.png" />
How can I get the lion to show up for only a second when any img.cat is clicked, and show up in that cat's exact position?
instead of $(this).remove() try to replace the cat with lion
var $lion = $('<img id="replacement" src="http://images1.wikia.nocookie.net/__cb20130326142633/warriors/images/4/47/Lion.png" />')
$(this).replaceWith($lion);
setTimeout(function () {
$lion.remove()
}, 1000)
Demo: Fiddle, Make sure the image is displayed for 1 sec

jQuery Plug-in to handle mousemove/drag with easing on a hidden div (kind of "inner zoom"

Actually I'm looking for a jQuery plug-in that can handle this:
there is a container with overflow hidden
inside of this is another one, which is way larger
when i move over the div, the part I'm seeing depends on my current position
when I'm in the left top corner I see the top left corner of the inner container
when I'm in the middle i see the middle of the container …
I wrote a little JavaScript that does that:
this.zoom.mousemove( function(event) {
var parentOffset = $(this).parent().offset();
var relativeX = event.pageX - parentOffset.left;
var relativeY = event.pageY - parentOffset.top;
var differenceX = that.zoom.width() - that.pageWidth;
var differenceY = that.zoom.height() - that.pageHeight;
var percentX = relativeX / that.pageWidth;
var percentY = relativeY / that.pageHeight;
if (1 < percentX) {
percentX = 1;
}
if (1 < percentY) {
percentY = 1;
}
var left = percentX * differenceX;
var top = percentY * differenceY;
that.zoom.css('left', -left).css('top', -top);
});
But this isn't very smooth and kinda jumpy, when you enter from another point of the container. So, before reinventing the wheel: Is there one plug in, that does exactly that and has iOS support (drag instead of mouse move)? All zoom plug ins (like Cloud Zoom) are over the top for this purpose and most have no support for dragging on iOS.
And if there's not something like this. How can I make this smoother and cooler. Any approach would be helpful. :)
Many thanks.
So, here is my solution - which works pretty well and is easy to achieve. There could be done some improvement, but to get the idea i'll leave it that way. :)
there is a demo on jsfiddle:
http://jsfiddle.net/insertusernamehere/78TJc/
CSS
<style>
div.zoom_wrapper {
position: relative;
overflow: hidden;
width: 500px;
height: 500px;
border: 1px solid #ccc;
cursor: crosshair;
}
div.zoom_wrapper > * {
position: absolute;
}
</style>
HTML
<div class="zoom_wrapper">
<img id="zoom" src="http://lorempixel.com/output/people-q-c-1020-797-9.jpg" alt="">
</div>
JAVASCRPT
<script>
var zoom = null;
// this function will work even if the content has changed
function move() {
// get current position
var currentPosition = zoom.position();
var currentX = currentPosition.left;
var currentY = currentPosition.top;
// get container size
var tempWidth = zoom.parent().width();
var tempHeight = zoom.parent().height();
// get overflow
var differenceX = zoom.width() - tempWidth;
var differenceY = zoom.height() - tempHeight;
// get percentage multiplied by difference (in pixel) cut by percentage (here 1/4) that is used as "smoothness factor"
var tempX = zoom.data('x') / tempWidth * differenceX / 4;
var tempY = zoom.data('y') / tempHeight * differenceY / 4;
// get real top and left values to move to and the last factor slows it down and gives the smoothness (and it's corresponding with the calculation before)
var left = (tempX - currentX) / 1.25;
var top = (tempY - currentY) / 1.25;
// finally apply the new values
zoom.css('left', -left).css('top', -top);
}
$(document).ready(function () {
zoom = $('#zoom');
//handle mousemove to zoom layer - this also works if it is not located at the top left of the page
zoom.mousemove( function(event) {
var parentOffset = $(this).parent().offset();
zoom.data('x', event.pageX - parentOffset.left);
zoom.data('y', event.pageY - parentOffset.top);
});
// start the action only if user is over the container
zoom.hover(
function() {
zoom.data('running', setInterval( function() { move(); }, 30) );
},
function() {
clearInterval(zoom.data('running'));
}
);
});
</script>
Note:
This one has, of course, no support for touch devices. But for that I use (again)/I can recommend the good old iScroll … :)

Categories

Resources