Getting Html From calling jQuery custom function - javascript

I created a custom function and am trying to call it in a separate function and get the elements html. What am I missing?
Custom Function: (wizard.js)
function wizard() {
var wizardBody = $(this).html();
console.log(wizardBody);
}
jQuery.fn.wizard = wizard;
Calling Said function on element: (config.js)
// Initiate Web Design Get Started Wizard
$("#webDesignGetStartedWizard").wizard();
I simply get undefined with the current code above, if I don't call the function on the html ($(this).html) then I get the following:
ƒ (e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w…
UPDATE
So the problem seems to be related to the use of my router plugin, jq-router Because if I take #webDesignGetStartedWizard out of the template and place it in my index file, it works perfectly.
https://github.com/muzammilkm/jq-router

It does work correctly make sure config.js and wizard.js loaded in the document correctly. You should load the wizard.js and then include config.js and also make sure the div#webDesignGetStartedWizard available when the script is called.
See a demo of your code.
function wizard() {
var wizardBody = $(this).html();
console.log(wizardBody);
}
jQuery.fn.wizard = wizard;
$(document).ready(function() {
// Initiate Web Design Get Started Wizard
$("#webDesignGetStartedWizard").wizard();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="webDesignGetStartedWizard">
<p>current text in the paragraph.</p>
</div>

Related

Can not access jquery in function. "Variable Scope" issue?

My ultimate goal is to have dynamic autocompletion on text input using typeahead jquery library.
In my HTML I put the input text field like this:
<input class="typeahead form-control" name="author_1" id="author_1" type="text"
placeholder="Type a part of author name or surname">
then in javascript I have this:
<script type="text/javascript">
function typeahead_initialize() {
var path = "{{ route('instructor_name') }}";
$('.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
}
typeahead_initialize ();
// Here typeahead is recognized as a function
// $('.typeahead').typeahead('destroy');
// Begin jQuery
$(document).ready(function() {
$("#addAuthorBtn").click(function() {
addAuthor();
});
$("#removeAuthorBtn").click(function() {
removeAuthor();
});
function addAuthor () {
// Destroy the typeahead system
// The problem is here: typeahead is not recognized
// as a functon here. It seems I can not reach
// jquery functions here.
$('.typeahead').typeahead('destroy');
// I add the dynamic input here, I deleted the unrelated code
// Reinitialize typeahead system again to include
// the dynamically added text input
typeahead_initialize ();
}
function removeAuthor () {
// Destroy the typeahead system
$('.typeahead').typeahead('destroy');
// I remove the dynamic input here, I deleted the unrelated code
// Reinitialize typeahead system again to include
// the dynamically added text input
typeahead_initialize ();
}
});
</script>
I explained in comment where the problem is. The auto-completion works for the first static input. But the second dynamically added input is not offering autocomplete, which I suspect I must destroy the typeahead and rerun it again. I guess the 'this' object inside addAuthor() function does not point to the same 'this' which is outside of $(document).ready(function() {}). How can I solve this? I cannot destroy and reinitialize the typeahead system when user clicks the add or remove button.
The official error I get is:
TypeError: $(...).typeahead is not a function
Update:
This is not related to forgetting to include jquery library, these are the libraries that I have included so far (I am using Laravel so the formatting is a bit odd) I guess it is related to "scope". The autocompletion actually works! so it means "typeahead" library is included properly. It just does not work when I call the typeahead from "inside a function".
<script src="{{ URL::to('js/jquery-3.1.1.js') }}"></script>
<script src="{{ URL::to('js/bootstrap3-typeahead.min.js') }}"></script>
Thing you did wrong is invoking typeahead_initialize() in script directly. Put this function in document.ready and all will go smoothly.
I just copied your code and did some modification check jsfiddle below, see log in console also
https://jsfiddle.net/Ld1wcy03/
OK I found the problem by myself. The problem comes because I use Laravel and it adds some scripts via app.js at the button of my view that causes this problem.
Probably the Laravel framework adds jQuery library by itself and two instances of it causes this issue.Removing the Laravel scripts solved the issue.

Where should I initialize select when using Materialize and Meteor?

I'm trying to use Materialize Forms on Meteor. On its Materialize's page it says I should init the "select" input field like this:
$(document).ready(function() {
$('select').material_select();
});
I've tried calling this on Meteor.startup, Template.body.created - nothing worked. I get the following error:
undefined is not a function (evaluating '$('select').material_select()')
Where should I initialize it?
Use the template's .rendered callback
<template name="hello">
<select><option>...</option></select>
</template>
Then you can have this in your js file
Template.hello.onRendered(function() {
$('select').material_select();
});
The template is added to the body most likely after rendered has already fired so thats why the body rendered didn't work. If you use .created the DOM hasn't rendered yet.
Akshat's answer is correct but if it still doesn't work for you, there might be a problem with subscription not fired yet or not every needed part of DOM beeing rendered. Use afterflush then.
Template.listing.onRendered(function () {
var template = this;
template.subscribe('listOfThings', function () {
Tracker.afterFlush(function() {
template.$('select').material_select();
});
});
});
Here is a conversation about that: https://github.com/meteor/meteor/issues/4401#issuecomment-103340262
And the docs: http://docs.meteor.com/api/tracker.html#Tracker-flush

Scripts not running when using get function in jquery

I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.

Call JS function with attributes from another file

I have a JS file with a simple function, matching width\heights of divs.
How can I call this function using attributes from HTML file.
In other words, I want to write a function matchHeight(div1,div2) in an outside file but call it from wherever i want using the divs I want.
The function exists, I just don't know how to call it the way I want.
Sorry if I didn't explain myself clearly.
Thanks.
If you write your MatchHeights(d1,d2){ ... } function in a JS file and link the file in your HTML page like you normally would link any JS file, then you can call the function in any part of your page, as long as you call the function after the linked file has been loaded by the browser.
Infact, you could even call it in other JS files, as long as the original containing file is loaded before the other ones by the browser.
To get the function to run the moment the page loads, call the function in the onload event of the body tag:
<script type="text/javascript">
var div1 = (some code to get the element)
var div2 = (some code to get the element)
</script>
...
...
<body onload="matchHeight(div1,div2)">
You must link the .js file in your .html file like this:
<head>
<script src="yourJSFile.js" type="text/javascript"></script>
</head>
<body onLoad="yourFunction();">
</body>
A really common pattern in jQuery that you can apply is passing in the CSS selector. It's easiest if you can just pass in the div's IDs, but other solutions will work also.
First off take any arguments out of your init string. It's way to complicated. Try this instead:
<body onload="init()">
function init() {
matchHeight("id1", "id2");
}
Once you have that you get the actual div in those functions like this:
function matchHeight(id1, id2) {
var div1 = document.getElementById(id1)
var div2 = document.getElementById(id2)
// .. other stuff
}
If you're using jQuery I'd recommend simplifying this even more, by taking the init() function off of the body tag completely, replacing it with jquery(document).load(function() { and using normal CSS selectors instead....matchHeight("#id1", "#id2") and var $div1 = $(id1);, but either way will work :)

Failing to load jScrollPane dynamically with content?

I want to reinitialise jScrollPane when new content is added loaded to the div, heres what I got so far:
var pane = $('.content_pane')
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
$('.content_pane').jScrollPane();
pane.reinitialise();
}
It sort of breaks the page, but I'm new to JavaScript so I figure probably doing something wrong.
Updated :
function loadContent() {
$('#content').load(toLoad,'',showNewContent)
}
function showNewContent() {
$('#content').show(1,hideLoader());
$('.content_pane').jScrollPane();
pane.reinitialise();
}
It still only loads once?!
Update 2:
function loadContent() {
$('#content').load(toLoad,'',showNewContent)
}
function showNewContent() {
$('#content').show(1,hideLoader());
$('.content_pane').jScrollPane();
var api = $('.content_pane').jScrollPane(
{
showArrows:true,
maintainPosition: false
}
).data('jsp');
api.getContentPane();
api.reinitialise();
}
HTML :
<div id="content_pane" class="content_pane">
<div id="content" >
<!-- content delivered here -->
</div>
</div>
It's quite straight forward.
This code:
$('.content_pane').jScrollPane();
pane.reinitialise();
Is called before you receive data. Consider moving this code to showNewContent.
And remove() from showNewContent(). It is callback. You should give function, not call it. Call to jScrollPane should be made only once.
Here is corrected version:
$('.content_pane').jScrollPane();
function loadContent() {
$('#content').load(toLoad,'', function(){
showNewContent();
pane.reinitialise();
});
}
If you are using jScrollPane 2 you need to use the getContentPane method to get a reference to the pane to load the content into as in this example:
http://jscrollpane.kelvinluck.com/ajax.html
I'm not sure of the structure of your HTML (where #content is relative to .content-pane) so I can't give you a complete example. However another problem I notice in your code is that pane is a reference to the jQuery object containing your pane. If you want to get a reference to the API (which has the reinitialise method on it) then you'll need to access the .data('jsp') property after initialising jScrollPane. However there is no need to call reinitialise directly after jScrollPane anyway - they both have the same effect once a pane is initialised...

Categories