Calling javascript from javascript? - javascript

I don't even know what to call this, i'm very very new with javascript so i'm sure the answer is simple. The situation is this: A javascript script is building a search pane in html using another sites API. The amount of items in the list are undetermined, hence why it's grabbing them with javascript. I'm using Bootstrap Multiselect on one of the option lists that is generated from the API. I've got javascript generating the HTML correctly (option tags nested in a select tag, with a div wrapper around them) But now I need to put in the call script. in html this is done with:
`<script type="text/javascript">
$(document).ready(function() {
$('#example').multiselect();
});
</script>`
but since i'm building the elements with javascript, how do i do this? is it easier? more complicated. Like I said i'm a newbie at this so i'm at a complete loss.
Here's the chunk of code that generates the multiselect list. I don't fully understand the whole script that pulls the API data, but I rewrote this chunk and it seems to work.
function renderCheck (options, attr) {
var $wrapper = $('<select>').attr({id: attr.id, name: attr.id, style: 'display: block;', class: 'field col-12 mb1', multiple: 'multiple'})
var idKey = attr.primaryKey ? attr.primaryKey : 'Id'
$.each(options, function(i, item) {
var $itemWrapper = $('<option>').attr({class: 'filter-item', value:item[idKey]}).text(item.Name)
$wrapper.append($itemWrapper);
})
return $wrapper
}

Never could figure out the answer, possibly due to my own incompetence with javascript (pretty sure i couldn't write a hello world script in javascript if i had a gun to my head). Have decided to go another way that won't require me rewriting that section of code.

Related

Capitalise HTML Element Targeted by CSS Selectors Using jQuery

In line with previous questions, I have another jQuery problem that's doing my head in.
I have an Elementor widget that's outputting a list of attributes that I'm using as a filterable list, so basically, it's a bunch of a tags inside li's.
The problem is, these are being pulled from a different system (long story, not relevant to the question) and it is passing them across in all caps. I want them displaying as capitalised, but because of the nature of text-transform, CSS can't help me.
I've used text-transform to make them all lower case, and now I just want to use jQuery to capitalise them. It needs to be every word as some entries have multiple words in them. However, I'm not getting any results.
The css selectors needed to target the a tags are as follows:
.woocommerce-widget-layered-nav-list__item.wc-layered-nav-term a
I've tried loads of different scripts and messed with them for a good hour or two now and managed to get rid of errors (like $ is not a function) but cannot get the text to captialise.
I've mostly been trying exampls from [this thread][1].
Here is what I think is the closest I've come:
<script>
jQuery.fn.capitalize = function() {
jQuery(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
jQuery(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
return $word.toUpperCase();
}));
box.setSelectionRange(stringStart , stringEnd);
});
return this;
}
</script>
<script>
jQuery('.woocommerce-widget-layered-nav-list__item.wc-layered-nav-term a').capitalize();
</script>
I'm fully aware that it's not structured particularly well and I know it can be neater, but I have tried numerous ways around it to no avail.
This code is currently being run from a HTML widget in the Elementor archive template where this list appears.
I'd really appreciate it is someone could point out the probably really obvious problems so I can learn from how dumb I'm being.
Many thanks.

Using .html() to dynamically generate content but js styling is not applied after using .html()

I'm building a website to use with Cordova on mobile. I found this great javascript framework called nativedroid2. This framework generates html classes, effects and the like which are applied to html code.
Now what I am trying to do is dynamically generating html code in jQuery by using AJAX calls to a server (I want javascript to make the HTML to remove the load of the server). However when I try to use html() on some divs to load some HTML, the nativedroid javascript function does not apply to the HTML, so no styling is done and everything looks like I am not even using nativedroid2. I am not using AJAX calls yet because I was testing if the html() works with nativedroid.
var html1;
var html2;
function loadpage(id, data) {
generateContent(id, data);
$('[data-role="header"]').html(html1);
$('[role="main"]').html(html2);
}
function generateContent(id, data) {
html1 = "bunch of html for the header"
html2 = "bunch of html for the body"
Does anyone know a better alternative to html() or a fix to make this work?
Alternative for html()
You can use JavaScript function createElement()
var P_tag=$("#your_div_id").createElement('p');
This will create an element P-tag, after that, you can set text to it
P_tag.text("Text");
So I read online that I had to escape the quotation marks. I used an online tool for that. However the online tool made " into "", which is read as an empty string. Removing that fixed it.
Thank you for your time if you answered

lightbox not working on new content

Hy, I'm having some problems making lightbox (in my case slimbox 2) work
after new content is loaded. I understand that slimbox needs to be called again, but I tried almost everything.
Here is the code how new content is been loaded:
...var link = $('<a class="loadpost" href="javascript:">Load more</a>');
link.click(loadMore);...
loadMore is the function that loads new content. this is just a piece of code. if you need the whole code let me know.
Here is the slimbox code.
jQuery(function($) {
$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
});
the new content has the rel attributes but it wont work. can i combine the click function from above to call slimbox code again.
Long version:
Without more of the code (if you can, make a jsfiddle or something similar) it's hard to know if this is the only issue, but one immediate issue I'm seeing is that you're using jQuery's $(" ") wrong. You're supposed to put a selector in there, so that jQuery can find whatever it is you want it to find in the DOM; what you're feeding it is a string of HTML.
Browsers use HTML to make the DOM (Document Object Model) tree, which you can think of as an abstracted logic tree of your HTML; the DOM sees 'a.loadpost' as a parent of the text node inside of it (in this case, 'Load more'). CSS and Javascript/jQuery both find information from that abstracted logic tree in pretty similar ways. With a few exceptions, if you know how to target something with CSS, you know how to target it with jQuery -- just select whatever HTML you need to select the same way you would with CSS.
So, to tell jQuery to do something to a link with a class of 'loadpost', you simply write $('a.loadpost'). $("a.loadpost") works as well.
Short version:
var link = $('a.loadmore');

Use callback function to create variables and use in a html element

Firstly excuse my ignorance with any inaccurate information I provide I a very new to javascript, jquery and json.
Anyway I have a script which pulls data from a json file and displays in a webpage with the help of javascript, jquery, ajax(i think) and json.
There is a callback for when I get back the results:
function searchCallback(data) {
$(document.body).append('<h1>' + data.title + '</h1>');
}
And it works fine the like this. However I want data.title (json object) to be displayed in a html element of my choice without having to use $(document.body) because my page won't display correctly at I have other html elements outside the script.
As far as I know (excuse ignorance) with javascript I can possible add a variable and use it as follows:
var title = data.title;
And in my html:
<span id="title"></span>
or maybe there is cleaner way?
Anyway how do I achieve this. Thank you for any help!!
If you want to find an element and modify, jQuery makes this easy. Instead of $(document.body).append find an existing element by it's id, and then call the text method on it to replace the text inside that element with something new.
$('#title').text(data.title);

How to handle localization in JavaScript files?

I want JavaScript code to be separated from views.
I got the requirement to implement localization for a simple image button generated by JavaScript:
<img src="..." onclick="..." title="Close" />
What's the best technique to localize the title of it?
PS: I found a solution by Ayende. This is the right direction.
Edit:
I got Localization helper class which provides the Controller.Resource('foo') extension method.
I am thinking about to extend it (helper) so it could return all JavaScript resources (from "ClientSideResources" subfolder in App_LocalResources) for the specified controller by its name. Then - call it in BaseController, add it to ViewData and render it in Layout.
Would that be a good idea?
EDIT
Consider writing the necessary localized resources to a JavaScript object (hash) and then using it for lookup for your dynamically created objects. I think this is better than going back to the server for translations. This is similar to adding it via viewdata, but may be a little more flexible. FWIW, I could consider the localization resources to be part of the View, not part of the controller.
In the View:
<script type="text/javascript"
src='<%= Url.Content( "~/Resources/Load?translate=Close,Open" %>'></script>
which would output something like:
var local = {};
local.Close = "Close";
local.Open = "Open";
Without arguments it would output the entire translation hash. Using arguments gives you the ability to customize it per view.
You would then use it in your JavaScript files like:
$(function(){
$('#button').click( function() {
$("<img src=... title='" + local.Close + "' />")
.appendTo("#someDiv")
.click( function() { ... } );
});
});
Actually, I'm not too fussed about keeping my JavaScript code out of my views as long as the JavaScript code is localized in a container. Typically I'll set my master page up with 4 content area: title, header, main, and scripts. Title, header, and main go where you would expect and the scripts area goes at the bottom of the body.
I put all my JavaScript includes, including any for viewusercontrols, into the scripts container. View-specific JavaScript code comes after the includes. I refactor shared code back to scripts as needed. I've thought about using a controller method to collate script includes, that is, include multiple scripts using a single request, but haven't gotten around to that, yet.
This has the advantage of keeping the JavaScript code separate for readability, but also allows me to easily inject model or view data into the JavaScript code as needed.
Actually ASP.NET Ajax has a built-in localization mechanism: Understanding ASP.NET AJAX Localization
If you insist on keeping it separate, you could do something like:
//keep all of your localised vars somewhere
var title = '{title_from_server}';
document.getElementById('someImage').title = title;
Remember, if you use JavaScript code to initialize any text of elements, your site will degrade horribly where JavaScript isn't available.

Categories

Resources