Facing issue with Mouse Event - javascript

I am new to web development, so I am taking a Pluralsight course called "Building a Web App with ASP.NET Core RC1, MVC 6, EF7 & AngularJS" by Shawn Wildermuth. In his jQuery module, Shawn has this piece of code that works flawlessly for him:
var main = $("#main");
main.on("mouseenter", function() {
main.style = "background-color: #888;";
});
main.on("mouseleave", function() {
main.style = "";
});
I have a div with id="main" on my index.html page, js file is referenced, other jQuery functionality in the same file works, I just can't get this piece of code to work. I know it is not significant, but at this point it is personal. Any suggestions are helpful. Thank you!

As style is a property of native DOM element and main is a jQuery object. You can use .css() and .removeAttr() jQuery method to get the desired result.
var main = $("#main");
main.on("mouseenter", function() {
main.css("background-color": "#888");
});
main.on("mouseleave", function() {
main.removeAttr('style');
});

You can't access the style property like this. Try the following:
var main = $("#main");
main.mouseenter(function() {
main.css("background-color", "#888");
});
main.mouseleave(function() {
main.css("background-color", "none");
});

Try this:
var main = document.getElementById("main");
main.onmouseenter=function(){
main.setAttribute('style', 'background-color:#888;');
};
main.onmouseleave=function(){
main.removeAttribute("style")
};

Related

Materialize dropdown options

I want to use the options from here:
http://materializecss.com/dropdown.html#options (The docs don't say so much).
My app is a rails app that use the materialize gem with the asset
pipeline.
My code now looks like this:
ul#dropdown1.dropdown-content.z-depth-0
li
a Profile settings
li
a payments
a.dropdown-button.btn-large.btn-flat.waves-effect.menu_trigger href="#!" data-activates="dropdown1"
i.material-icons menu
javascript:
var elem = document.querySelector('.menu_trigger');
var instance = M.Dropdown.init(elem, {
coverTrigger: false,
constrainWidth: false,
});
In practice, using the data attribute isn't always the best way. Options can (or rather should be, correct me if I'm wrong) passed the following way:
// native javascript way
document.addEventListener('DOMContentLoaded', function() {
var dropdown1 = document.querySelector('.simple-dropdown');
var dropdownOptions = {
'closeOnClick': true,
'hover':true
}
var instanceDropdown1 = M.Dropdown.init(dropdown1, dropdownOptions);
});
// Initializing the jQuery way
$(".simple-dropdown").dropdown(
{
'closeOnClick': true,
'hover': true,
});
Solved!
Finally like it says here http://archives.materializecss.com/0.100.2/dropdown.html#options
Solved where it says:
To use these inline you have to add them as data attributes. If you
want more dynamic control, you can define them using the jQuery plugin
below.
So then, with something like this:
a.dropdown-button.btn-large.btn-flat.waves-effect href="#!" data-activates="dropdown1" data-beloworigin="true"
i.material-icons menu
Done what i wanted
Couldn't find directly in Materialize docs, but by trial and error I found this javscript code is working fine. It looks like an expected options variable should be an Object with property "dropdownOptions" with assigned another Object with properties listed in docs.
document.addEventListener('DOMContentLoaded', function () {
var options = {
dropdownOptions: {
alignment: 'right',
hover: true
}
}
var elems = document.querySelectorAll('.dropdown-trigger');
var instances = M.Dropdown.init(elems, options);
});

JQuery doesn't work with the after created element

I want to create some css card with the data retrieved from json. It iterates fine, but I have a problem with the animation. When the user press a button, the card makes an animation and shows more info. The problem is that the animation works just with the first card. How can I solve it? Thank you.
HERE you can find the full code.
This is the script linked to the info's button:
(function(){
'use strict';
var $mainButton = $(".main-button"),
$closeButton = $(".close-button"),
$buttonWrapper = $(".button-wrapper"),
$ripple = $(".ripple"),
$layer = $(".layered-content");
$mainButton.on("click", function(){
$ripple.addClass("rippling");
$buttonWrapper.addClass("clicked").clearQueue().delay(1500).queue(function(){
$layer.addClass("active");
});
});
$closeButton.on("click", function(){
$buttonWrapper.removeClass("clicked");
$ripple.removeClass("rippling");
$layer.removeClass("active");
});
})();
ok your issue is you not detect good element. i have modify your script.js
$(document).on("click",".main-button", function(){
$(this).find(".ripple").addClass("rippling");
$(this).closest("main").find(".button-wrapper").addClass("clicked").clearQueue().delay(1500).queue(function(){
$(this).closest("main").find(".layered-content").addClass("active");
});
});
please try: http://plnkr.co/edit/qZmi3jJS4WVcN676OSP2
UPDATE for close
Try
$(document).on("click",".close-button", function(){
$(this).closest("main").find(".button-wrapper").removeClass("clicked");
$(this).closest("main").find(".ripple").removeClass("rippling");
$(this).closest("main").find(".layered-content").removeClass("active");
});
link : http://plnkr.co/edit/WKtJUqOwkEGnhb2Zc1HZ

TypeError: this.$E_0.getElementsByTagName is not a function

I am attempting to create a modal dialog in sharepoint 2010, but I'm getting this error:
TypeError: this.$E_0.getElementsByTagName is not a function
my code is:
var options = SP.UI.$create_DialogOptions();
options.html = '<div class="ExternalClass23FFBC76391C4EA5A86FC05D3D9A1904"><p>RedConnect is now available.​</p></div>';
options.width = 700;
options.height = 700;
SP.UI.ModalDialog.showModalDialog(options);
using firebug, i tried simply using the url field instead of the html field and it gave no error.
also related to this, what does SP.UI.$create_DialogOptions() actually do? what is the difference between using it and simply using a dict of values for your options?
options.html requires a HTML DOM element instead of plain HTML code:
<script>
function ShowDialog()
{
var htmlElement = document.createElement('p');
var helloWorldNode = document.createTextNode('Hello world!');
htmlElement.appendChild(helloWorldNode);
var options = {
html: htmlElement,
autoSize:true,
allowMaximize:true,
title: 'Test dialog',
showClose: true,
};
var dialog = SP.UI.ModalDialog.showModalDialog(options);
}
</script>
Boo
Example code taken from the blog post Rendering html in a SharePoint Dialog requires a DOM element and not a String.
also related to this, what does SP.UI.$create_DialogOptions() actually do? what is the difference between using it and simply using a dict of values for your options
When you look at the definition of the SP.UI.DialogOptions "class" in the file SP.UI.Dialog.debug.js you see that its a empty javascript function.
SP.UI.DialogOptions = function() {}
SP.UI.$create_DialogOptions = function() {ULSTYE:;
return new SP.UI.DialogOptions();
}
My guess is that it is there for client diagnostic purpose. Take a look at this SO question: What does this Javascript code do?

Mustache.js + jQuery: what is the minimal working example ?

I would like to use mustache.js with jQuery in my HTML5 app, but I can't make all the component work together. Every file is found, there is no problem here (the template is loaded roght, I can see its value in the Firebug debugguer).
Here is my index.html :
<!DOCTYPE html>
<html lang="fr">
<head><meta charset="utf-8"></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="../js/jquery.mustache.js"></script>
<script src="../js/app.js"></script>
<div id="content"></div>
</body>
</html>
Here is my app.js file :
$(document).ready(function() {
var template = $.get('../templates/article.mustache');
$.getJSON('../js/article.json', function(view) {
var html = Mustache.to_html(template, view);
$("#content").append(html);
});
});
The jquery.mustache.js file is the one generated from https://github.com/janl/mustache.js :
/*
Shameless port of a shameless port
#defunkt => #janl => #aq
See http://github.com/defunkt/mustache for more info.
*/
;(function($) {
// <snip> mustache.js code
$.mustache = function(template, view, partials) {
return Mustache.to_html(template, view, partials);
};
})(jQuery);
Noting is displayed. Firebug tells me
Mustache is not defined
See capture :
I know something is missing, but I can't tell what.
Thanks.
EDIT:
The correct and complete answer to a minimal example is the following :
write the template in the script, do not load it from a file
idem for the json data
read how the jQuery is generated and use $.mustache.to_html function instead of the (documented on github) Mustache.to_html (thanks to #mikez302)
refactor 'till you drop
$(document).ready(function() {
var template = " ... {{title}} ... ";
var json = {title: "titre article" }
var article = $.mustache(template, json);
$("#content").append(article);
});
But, it is easy to read the json from another file :
$(document).ready(function() {
var template = " ... {{title}} ... ";
$.getJSON('../js/article.json', function(view) {
var article = $.mustache(template, view);
$("#content").append(article);
});
});
You can finally also read the template from a file :
$(document).ready(function() {
$.getJSON('../js/article.json', function(view) {
$.get("../templates/article.mustache", function(template) {
var article = $.mustache(template, view);
$("#content").append(article);
});
});
});
Working example (without loading order problems) :
$(document).ready(function() {
$.getJSON('../js/article.json', function(model) { return onJSON(model); });
});
function onJSON(model) {
$.get("../templates/article.mustache", function(view) {
var article = $.mustache(view, model);
$("#content").append(article);
});
}
In place of Mustache.to_html, try $.mustache. It looks to me like the Mustache variable is defined within the function, so it is not directly accessible outside of it.
I know this question already ahs been answered, however I wrote a blog post on precisely this topic and thought I would share it here so anyone looking for examples of how to use Mustache with jQuery might see it.
http://blog.xoundboy.com/?p=535

jquery templating - import a file?

I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:
var context = {
name: this.model.get('name'),
email: this.model.get('email')
}
var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";
var html = Mustache.to_html(template, context);
$(this.el).html(html);
$('#app').html(this.el);
I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.
Tips?
Updated (4/11/14):
As answered by OP below:
Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender
Original Answer:
I just used this a couple of hours ago:
http://api.jquery.com/category/plugins/templates/
It's an official jQuery plugin(i.e. the devs endorse it).
This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/
Here's the code to have a template in HTML:
<script id="titleTemplate" type="text/x-jquery-tmpl">
<li>${Name}</li>
</script>
___________
// Compile the inline template as a named template
$( "#titleTemplate" ).template( "summaryTemplate" );
function renderList() {
// Render the movies data using the named template: "summaryTemplate"
$.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
}
It's in a <script> tag, because that's not visible by default.
Note the type="text/x-jquery-tmpl". If you omit that, it will try to parse it as JavaScript(and fail horribly).
Also note that "loading from a different file" is essentially the same as "reading a file" and then "loading from a string".
Edit
I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl
I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)
var TEMPLATES = {};
var Template = {
load: function(url, fn) {
if(!TEMPLATES.hasOwnProperty(url)) {
$.ajax({
url: url,
success: function(data) {
TEMPLATES[url] = data;
fn(data);
}
});
} else {
fn(TEMPLATES[url]);
}
},
render: function(tmpl, context) {
// Apply context to template string here
// using library such as underscore.js or mustache.js
}
};
You would then use this code as follows, handling the template data via callback:
Template.load('/path/to/template/file', function(tmpl) {
var output = Template.render(tmpl, { 'myVar': 'some value' });
});
We are using jqote2 with backbone because it's faster than jQuery's, as you say there are many :)
We have all our templates in a single tpl file, we bind to our template_rendered so we can add jquery events etc etc
App.Helpers.Templates = function() {
var loaded = false;
var templates = {};
function embed(template_id, parameters) {
return $.jqote(templates[template_id], parameters);
}
function render(template_id, element, parameters) {
var render_template = function(e) {
var r = embed(template_id, parameters);
$(element).html(r);
$(element).trigger("template_rendered");
$(document).unbind(e);
};
if (loaded) {
render_template();
} else {
$(document).bind("templates_ready", render_template);
}
}
function load_templates() {
$.get('/javascripts/backbone/views/templates/templates.tpl', function(doc) {
var tpls = $(doc).filter('script');
tpls.each(function() {
templates[this.id] = $.jqotec(this);
});
loaded = true;
$(document).trigger("templates_ready");
});
}
load_templates();
return {
render: render,
embed: embed
};
}();
They look like
<script id="table" data-comment="generated!!!!! to change please change table.tpl">
<![CDATA[
]]>
</script>

Categories

Resources