I am trying to append a new list item based on a condition using jquery. For reference the page is a Wordpress page and i have been able to implement serval jquery scripts using same format.
Here is the sample HTML.
<div class = "bag" id = "bag" style="width: 100%; padding: 0 0 0 5px; float: left;">
<ul id = "clubsli" name = "clubsli" class = "clubsli">
I dynamically create a li with "n" values and want to append a new li to the end of this list using JavaScript/jQuery script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function addClub() {
$roleint = 2613;
$count = $("#clubsli li").length - 1;
if ($roleint == 2613) {
if ($count < 100) {
$("#bag ul").append('<li>$roleinit</li>');
};
};
};
});
</script>
No matter what I do I get the following Unexpected token ILLEGAL error that seems to not like the "<" in the list element.
Here is the error I receive.
I've tried appending a non-li and can without fail and tried "appendTo" but get same error on the "<".
Your code is basically okay. Here's a working JSFiddle version of it, with the following problems or incompletenesses corrected:
$(document).ready(function () {
function addClub() {
$roleint = 2613;
$count = $("#clubsli li").length - 1;
if ($roleint == 2613) {
if ($count < 100) {
$("#bag ul").append('<li>' + $roleint + '</li>');
};
};
};
addClub();
});
You needed to use the string appending operator + in your appended string.
You'd typo'd $roleint as $roleinit in your append()
You'd declared the addClub() function, but not actually called it. I presume it was being called somewhere else in your code?
In addition, as Guido points out, it's quite odd to use variable names starting with $ in jQuery unless the variable is actually a jQuery object, so that makes your code read quite strangely.
I don't think any of this would have caused the error in your question, though, so perhaps there's something else going on that we can't see from your description?
Problem solved! Similar post on WordPress specific stackexchange shows how to edit functions.php so WP does not auto-insert page breaks.
https://wordpress.stackexchange.com/questions/101368/wordspress-add-p-into-my-javascripts
Thanks to those that helped clarify what was causing the problem for me. Gave me better idea on where to look.
Related
I have the following code inside a file called additional.js for a WordPress website I'm working on:
// Fade in for news posts
jQuery(".elementor-post").each(function(i) {
jQuery(this).delay(250 * i).fadeIn(1000);
});
// Alphabetical Filter for Products
var $boxes = $('.elementor-posts-container > .elementor-post');
var $btns = $('.alphabet-btn').click(function() {
var id = this.id;
if (id == 'all') {
$boxes.show()
} else {
$boxes.hide().filter(function() {
var re = new RegExp('^' + id, 'i');
return re.test($(this).text().trim());
}).show()
}
$btns.removeClass('alphabet-active');
$(this).addClass('alphabet-active');
})
The first part is a simple timed fade in for my blog posts and the second part is the js for an alphabetical filter on my products page.
Currently, the alphabetical filter is acting strangely. If you go here and click on B, for example, http://staging.morningsidepharm.com/products/generic-medicines/ if filters and leave the product beginning with B but then it fades in all of the other products after this - This is only on the initial click... after that, when you click around it seems to be acting as it should.
If I remove the first bit of code from the top of my file:
jQuery(".elementor-post").each(function(i) {
jQuery(this).delay(250 * i).fadeIn(1000);
});
Everything in the alphabet search works correctly, even on the initial click.
Which makes me believe there is something conflicting in the two bits of code.
Do I need to END the first bit of code somehow? or I there something else conflicting here?
I tried separating them and putting them in different .js files, but I guess that doesn't work because they both are still fired when the page loads.
Any help would be greatly appreciated, I'm so close! :)
In the first part you use a syntax of JQuery() and in the second you use another $() test by changing JQuery() by $() in the first part of your code, maybe that makes conflict.
Ok, I found the issue.
In the first bit of code, I'm targeting the .elementor-post selector without being specific to which .elementor-post I want to target. This meant it would affect the div .elementor-post sitewide.
Adding a container class and changing the top part of the code to the following fixed things:
// Fade in for news posts
jQuery(".fade-in-post-container .elementor-post").each(function(i) {
jQuery(this).delay(250 * i).fadeIn(1000);
});
I need to add some CSS class based on some condition using JavaScript but facing issue in case my string contains a forward slash (/). This is what my use case is
<div id="div_product-size-icon-121NM/L" class="disabled"></div>
<script>
var newProductCode = '121NM/L';
if( newProductCode.contains('/') ){
newProductCode = newProductCode.replace('/','/\//');
$('#'+'div_product-size-icon-'+newProductCode).addClass('active');
}
</script>
I have even tried newProductCode.replace('/','/\'); but while running code, I am facing following error
JavaScript error: SyntaxError: unterminated string literal
I can not change HTML along with product code; the option for me is to change it in JS.
Here is a working js example: JS code
I have first replaced the if statement with indexOf() and changed the .replace function as .replace('/', '\\/');
var newProductCode = '121NM/L';
if (newProductCode.indexOf('/') > 0) {
alert('Once you click OK, the text will disappear!!');
newProductCode = newProductCode.replace('/', '\\/');
$('#' + 'div_product-size-icon-' + newProductCode).addClass('active');
}
div.active {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_product-size-icon-121NM/L" class="disabled">Some text here</div>
#Pugazh probably has the correct way of doing it, but you could just isolate the string in " by searching using an attribute in jQuery. Here's a link to the API documentation. It avoids having to do the replace altogether. It's a hacky way of doing it.
var newProductCode = '121NM/L';
$('[id="div_product-size-icon-'+newProductCode+'"]').addClass('active');
I'm using simplepie to pull in two rss feeds. Using a PHP foreach loop, I then echo the information each feed post contains in the class .story_overview and adding a .pin class for each article. I'm using jQuery within the PHP foreach to hide.story_overview and add a unique identifying number to the end of the .story_overview and respective .pin class and this is working:
<script>
$('.story_overview').hide();
$('.pin').attr('class','pin' + i);
$('.story_overview').attr('class','story_overview' + i);
i++;
</script>
I'm trying to reach the desired outcome of hovering over a .pin revealing the respective .story_overview (so .pin1 would reveal .story_overview1). I'm currently trying to do this with a JavaScript for loop but it refuses to work:
<script>
for (x = 0; x <= i; x++){
$('.pin'+ x.toString()).mouseover(function(){
$('.story_overview' + x.toString()).show();
});
$('.pin'+ x.toString()).mouseout(function(){
$('.story_overview' + x.toString()).hide();
});
};
</script>
I have tested all the jQuery commands by trying the same code but with the identifying numbers at the end of the class names (rather than x.toString) and placing the code outside of the for loop, and that all works.
Any help what so ever would be greatly appreciated! Thanks in advance.
You can simply do this:
$('.pin').mouseover(function(){
$('.story_overview').eq($(this).index()).show();
}).mouseout(function(){
$('.story_overview').eq($(this).index()).hide();
});
You can achieve the desired output by using the .eq() method with .index() to get the index of the hovered element.
Or you might like this:
$('.pin').mouseover(function(){
$('.story_overview'+$(this).index()).show();
}).mouseout(function(){
$('.story_overview'+$(this).index()).hide();
});
Ok so I finally figured out which part of my code is causing the exception. You can read the initial post here. The code in the initial post is missing the part which is actually causing the exception (the manual subscription to the viewPortData observable). Apparently, I'm doing it wrong somehow... Here's the code:
self.viewPortData = ko.observable();
self.viewPortData.subscribe(function (newValue) {
var viewPort = $('#metro-view-port');
if (viewPort && newValue) {
self.fadeInOut(viewPort, newValue);
}
});
self.fadeInOut = function (domObject, newContent) {
if (newContent) {
var currentContent = domObject.html();
if (currentContent) {
var wrappedContent = $(currentContent);
wrappedContent.fadeOut(400, function () {
wrappedContent.empty();
domObject.html(newContent).hide().fadeIn(400);
});
} else {
domObject.html(newContent).hide().fadeIn(400);
}
}
};
So where did I go wrong?
The same error occurred to me. The problem was caused because the HTML had comments on it. Something like:
<!-- Some Comment goes here -->
<div>
...
</div>
To fix that, without changing the HTML, you need to wrap the HTML with something else, so you pass only one element to jQuery:
var div = document.createElement( 'div' );
div.innerHTML = nativeHtml;
var $html = $( div );
I created a fiddle using your code from this post and the previous post, and it works as it should.
However, I'm only returning a simple <div> tag to populate the HTML of the metro-view-port <div>.
My best guess is that the HTML that you're returning is the problem.
My advice to you is to first confirm this by reducing the HTML returned to something very simple, and then gradually reintroduce the intended code until you find the problem.
Flip your fadeIn(400) to a show().
It is simpler for jQuery to do the math for.... I think that it can't get computed style of the elements due to some floats inside it or something.
I had the same problem..... but after some research I got to here (DAMMET I LOST THE TAB - it was a jQuery bug report anyway ) and realised what needed to be fiddeled with to fix it.
In my code I swapped out fadeIn() to show() so it isn't to do with the animation
you would have thought that without the animation the problem wouldn't be prevalent either - but it is.
try slideDown(0 if your still after an animation, it might not work but its worth a pop.
This bug was in old versions of jQuery. Try to change .hide() to .css('display', 'none')
According to this jQuery bug, the problem may have to do with newline characters and whitespace text nodes in your HTML. In my case, I was taking a template like this one:
<script id="myTemplate" type="text/template">
<div>
<h2>Important stuff</h2>
</div>
</script>
And parsing it like this:
var currentContent = $.parseHTML($('#myTemplate').html());
So I ended up with a bunch of text nodes representing the newline and whitespace characters in the original HTML template. Probably something similar has happened to you.
To fix this, I stripped out the newlines and whitespaces like so:
$('#myTemplate').html().replace(/\n/g, '').replace(/>\s+</g, '><').trim();
Hope that helps someone!
I am trying to avoid hard-coding each instance of this WYSIWYG editor so I am using jQuery to create an each() loop based on function name. Annoyingly InnovaStudio seems to explode when I try.
Documentation
Attempt #1
<script type="text/javascript">
/*
id = $(this).attr('id');
if(id.length == 0)
{
id = 'wysiwyg-' + wysiwyg_count;
$(this).attr('id', id);
}
WYSIWYG[wysiwyg_count] = new InnovaEditor('WYSIWYG[' + wysiwyg_count + ']');
WYSIWYG[wysiwyg_count].REPLACE(id);
*/
var demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1');
console.log('loop');
</script>
Effect
Works fine, but of course only works for a single instance of the editor. If I want multiple instances I need to use an each.
Attempt #2:
<script type="text/javascript">
var wysiwyg_count = 1;
//var WYSIWYG = [];
var demo;
(function($) {
$(function() {
$('.wysiwyg-simple').each(function(){
/*
id = $(this).attr('id');
if(id.length == 0)
{
id = 'wysiwyg-' + wysiwyg_count;
$(this).attr('id', id);
}
WYSIWYG[wysiwyg_count] = new InnovaEditor('WYSIWYG[' + wysiwyg_count + ']');
WYSIWYG[wysiwyg_count].REPLACE(id);
*/
demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1');
console.log('loop');
});
});
})(jQuery);
</script>
Effect
Replaces the entire HTML body of my page with JUST WYSIWYG related code and complains as no JS is available (not even Firebug, so can't debug).
Notice that I am hardcoding the name still. I only have one instance on the page I am testing it on, so when I get this hard-coded name working I will get the commented out code working along the same lines.
Does anybody know what the hell is going on here?
Solution: Don't bother trying to use InnovaStudio, went with CKEditor instead.
Even though you went for CKEditor you might be interested in a solution. You can supply a second argument to the REPLACE function. This second argument should also be a id, id from a element able to accept html output (like div, span, p).
demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1', 'wysiwyg-1-replaceDiv');
When the second argument is left out, InnovaStudio, writes the html output to the document by simply using:
document.write();
Hope this helps!
Why don't you use their own initialization code since version 4.3:
<textarea class="innovaeditor">
content here...
</textarea>
<script>
oUtil.initializeEditor("innovaeditor",
{width:"700px", height:"450px"}
);
</script>
The method is oUtil.initializeEditor(selector, option). The first parameter is selector and second is editor properties in JSON format.
The selector can be:
Css class name, if class name is specified all textareas with specified class name will be replaced with editor.
Textarea Id. If it is an Id, a prefix '#' must be added, for example oUtil.initializeEditor("#mytextarea").
Textarea object.
The second parameter is editor's properties. All valid editor's properties can be specified here for example width, height, cmdAssetManager, toolbarMode, etc.
Note that this method can be called from page onload or document ready event or during page load (as long as the object referred by selector are already rendered). This method available automatically when the page include the editor script.