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..
This isn't the same jquery code but it's similar and it's what I would like, the div floats around the entire page, I've tried using this code as well but I still get the same problem as above. http://jsfiddle.net/Xw29r/15/