I have the following code which loads jQuery into the page dynamically after page load and then attempts to run some jQuery of its own afterwards. The first console log of the page title works. The issue comes when it cant find the class "special-div" later on in the page and replace it with the appropriate text. Any thoughts?
//Load jQuery library using plain JavaScript
(function(){
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(newscript);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
console.log( 'jQuery is loaded on: ' + $('title').text() );
$( '.special-div' ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
$( this ).replaceWith( "Say something here " + $( this ).attr( "id" ) + ' ' + $( this ).attr( "title" ) );
});
});
})();
The HTML looks like this:
<div id="something" class="special-div" title="else"> </div>
The wacky CMS that I am working on only allows for me to paste in one external javascript file so i have to load in jQuery and all other scripts i need through that one file.
Edit:
so i ran a few additional tests and tried this:
console.log( 'jQuery is loaded on: ' + $( '.special-div' ).attr( "id" ) );
the response i am getting is:
jQuery is loaded on: undefined
If you want to return content of div in second console.log, use $( this ).html() instead of $( this ).text()
If you want to replace text for each $( '.special-div' ) with the content of their attributes, you have to do:
$( this ).replaceWith( "Say something here " + $( this ).attr( "id" ) + ' ' + $( this ).attr( "title" ) );
instead of
$( '.special-div' ).replaceWith( "Say something here " + $( this ).attr( "id" ) + ' ' + $( this ).attr( "title" ) );
otherwise you get the same replacement for all occurrences.
I tried it and it works.
But if you are putting it in <head> and another jQuery is loaded before it, DOM searching will run before the DOM getting ready so that it can not find the DOM.
(case of no window.setTimeout(function() { checkReady(callback); }, 100);)
(another CMS plugin might load jQuery)
So it could be better to run the script on kind of window.onload timings.
Or putting it on the end of <body> may also work.
Related
I'm trying to loop each thru of the attribute and if it matches, it will replace the inner HTML of the DOM. For this example, I'm trying to replace the data-product="momentum-shorts-2-0" inner HTML DOM which is the <h2>Momentum Shorts 2.0 NEW</h2> contents into the <div> class="compare-main" </div> that I've highlighted in the screenshot..
This is what I have with my code now but i'm stuck.. it keeps returning to me singular value of the last item..
<script>
jQuery( document ).ready(function() {
$( ".compare-filter-item" ).click(function() {
var selected_data_product = $(this).attr("data-product");
$(".compare-all .compare-products [data-product='" + selected_data_product + "']").each(function(){
new_html = $(this).html();
$(".compare-main .compare-products [data-product='" + selected_data_product + "']").each(function(){
$(this).html(new_html);
})
});
});
})
</script>
Issue:
<script>
jQuery( document ).ready(function() {
$( ".compare-filter-item" ).click(function() {
var selected_data_product = "momentum-shorts-2-0";
$(".compare-main .compare-products [data-product='" + selected_data_product + "']").each(function(){
$(this).find("h2").text("Momentum Shorts 2.0");
});
});
})
</script>
I tried to understand your requirement and here is the solution see if it help.
$.get( load_this, function( page ) {
$article = $( page ).find( ".js-Article--current" );
console.log( $(page) );
$article.removeClass( "js-Article--current" ).addClass( "Article--contentHidden" )
.children( ".js-ArticleHeader" ) .addClass( "ArticleHeader--teaser" )
.find( ".next-teaserFade" ) .addClass( "ArticleHeader-teaserFade" )
.end()
.find( ".next-teaserSqueeze" ) .addClass( "ArticleHeader-teaserSqueeze" );
$( ".js-Article--current" ).after( $article );
});
get returns whole page.
Now problem I've encountered is this:
if js-Article--current is not top level element find finds it.
if js-Article--current is top level element find cannot find it.
Why?
p.s. I know solution: filter instead of find. But why is find behaving like this? I don't get it.
find() will try to find a child element of the selector. So, if .js-Article--current is the selector, it will not find it.
filter(), instead, filters through the selectors
Check the console:
var findTest = $('div').find('#test').length;
var filterTest = $('div').filter('#test').length;
console.log('find test: ' + findTest);
console.log('filter test: ' + filterTest);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test"></div>
<div id="anotherTest"></div>
Consider the following codes:
Load JS
$( "<script src=\"test.js\"><\/script>" ).on( "load",
function() {
console.log( "JS LOADED" );
}
).appendTo( $( "head" ) );
Load CSS
$( "<link rel=\"stylesheet\" href=\"test.css\" />" ).on( "load",
function() {
console.log( "CSS LOADED" );
}
).appendTo( $( "head" ) );
Can someone please explain me why the load event will not trigger for the js file. And what should be done to make it work ?
I'm using the 'nested-list' plugin for jQuery Mobile, this one:
The problem is that when you use more than one level the plugins fails going back. For example, in the fiddle I have created I can go to 'Test 1.2.1' without problem, If I going back 1 level it works fine and I go to 'Test 1.2', but then if I tried to go up one level more (it was 'Test1') it goes up 2 levels (to 'Test').
I have checked the plugin code but I can't find the problem and I have left a message in the Git forum with no answer. Maybe someone could help me here.
Thanks in advance!
Fiddle
Looking at the plugin code, it is only designed for one level deep nesting. This is because the developer chose to remove created subpages each time you click on a parent LI. So when you get to the second level of depth, its parent has been removed from the DOM and you have to click the back button twice to get to the original page.
I have made some changes to the plugin code that should solve this problem:
In _attachBindings, I have commented out the line that removes previously created subpages:
_attachBindings: function() {
this._on({
"click": "_handleSubpageClick"
});
this._on( "body", {
"pagechange": function(){
if ( this.opening === true ) {
this.open = true;
this.opening = false;
} else if ( this.open === true ) {
//Don't remove the old LI
//this.newPage.remove();
this.open = false;
}
}
});
},...
Then in _handleSubpageClick, I check if the subpage already exists in the DOM (via data attribute added when creating the page). If not, we go through the existing code that creates the subpage, and then in the end I store the created subpage id in a data attribute on the parent LI. If it does exist we just navigate to that page.
_handleSubpageClick: function( event ) {
if( $(event.target).closest( "li" ).children( "ul" ).length == 0 ) {
return;
}
this.opening = true;
//see if we already created the subpage
var $li = $(event.target).closest( "li" );
var pid = $li.data("nextpageid");
if (pid && pid.length > 0){
this.pageID = pid;
} else {
this.newPage = $( this.options.page ).uniqueId();
this.nestedList = $( event.target ).children( "ul" )
.clone().attr( "data-" + $.mobile.ns + "role", "listview" )
.css( "display", "block" );
this.pageName = (
$( event.target.childNodes[0] ).text().replace(/^\s+|\s+$/g, '').length > 0 )?
$( event.target.childNodes[0] ).text() : $( event.target.childNodes[1] ).text();
this.pageID = this.newPage.attr( "id" );
// Build new page
this.newPage.append(
$( this.options.header ).find( "h1" ).text( this.pageName ).end()
).append(
$( this.options.content )
).find( "div.ui-content" ).append( this.nestedList );
$( "body" ).append( this.newPage );
//save subpage id as data attribute of the LI
$li.data("nextpageid", this.pageID);
}
$( "body" ).pagecontainer( "change", "#" + this.pageID );
}...
Here is your updated FIDDLE
I removed the external link to the plugin and instead copied all the code into the javascript pane and made the edits. You should be able to copy that code directly and use as the updated plugin. (Of course I did this quickly and have not rigorously tested it, so make sure it works for you).
Apologies if this is an overly simple question, but my searches are getting me nowhere.
I have a jQuery function which produces an error on some of my pages which do not contain the #message input:
Error: jQuery("#message").val() is undefined
Line: 56
And my jQuery function:
function updateCountdown()
{
var $left = 255 - jQuery( '#message' ).val().length;
jQuery( '#countdown' ).text( $left + ' Characters Remaining' );
}
$( document ).ready( function()
{
updateCountdown();
$( '#message' ).change( updateCountdown );
$( '#message' ).keyup( updateCountdown );
});
So my question is, how do I use a conditional to remove the error message from pages without the #message input? I believe my problem is a basic lack of knowledge of how JavaScript works.
I wouldn't bother to perform an explicit test on the jQuery object returned from the selector — let jQuery do that for you!
$(function() {
$('#message').each(function() {
var $self = $(this);
$self.bind('change keyup', function updateCountdown() {
$('#countdown').text((255 - $self.val().length)) + ' characters remaining');
});
});
});
If '#message' doesn't match anything, then the .each( ... ) call won't do anything.
The only problem is with your init code.. after that it'll run fine. So do:
$( document ).ready( function()
{
$( '#message' ).change( updateCountdown ).keyup( updateCountdown ).keyup();
});
Note the use of chaining.
Improve your selector to ensure that it's actually getting an input element (so that there is a value). Then check to see if your selector actually matched anything before working with it. Note that the length of the jQuery object returned is the number of matching elements (it must be greater than 0). Oh, and you can consistently use the $ function as long as there aren't any conflicts with other javascript frameworks.
function updateCountdown()
{
var msg = $('input#message');
if (msg.length > 0) {
var $left = 255 - msg.val().length;
$( '#countdown' ).text( $left + ' Characters Remaining' );
}
}
You just need to check if the jQuery object contains any items. I would do it like this.
$( document ).ready( function()
{
var $message = jQuery( '#message' );
if($message.length > 0) {
updateCountdown();
$( '#message' ).change( updateCountdown );
$( '#message' ).keyup( updateCountdown );
}
});
Then I'd change your updateCountdown() function to use the this keyword rather than doing another jQuery lookup. jQuery sets this to be the DOM element the event occurred on.
function updateCountdown()
{
var $left = 255 - jQuery( this ).val().length;
jQuery( '#countdown' ).text( $left + ' Characters Remaining' );
}