I am trying to add custom Javascript into my Wordpress site. I have javascript being properly enqueued into the site. In order to stay compliant with html guidelines, I am trying to use classes for my header's on the accordion, which is why I'm using .accordion . and also using the substring to remove the hashmark from the url. If I change all of my classes to id's, take out the period in the selector, and also remove the substring for the trimming, it will work.
However, that will force me to use id's instead of classes. Is there any workaround for this or am I forced to use id's?
Non working code in override.js:
var hash = window.location.hash;
var begining= ".accordion .";
var trimmed = begining + window.location.hash.substring(1);
jQuery(document).ready(function() {
jQuery('.accordion').accordion({
active: false,
collapsible: true,
autoHeight: false,
heightStyle: "content"
});
jQuery(trimmed).click();
});
"Duct taped" working code in override.js
var hash = window.location.hash;
var begining= ".accordion ";
var trimmed = begining + window.location.hash;
jQuery(document).ready(function() {
jQuery('.accordion').accordion({
active: false,
collapsible: true,
autoHeight: false,
heightStyle: "content"
});
jQuery(trimmed).click();
});
Html that we want for page:
<div class="accordion">
<h3 class="zen-shi-apps">zen shi appetizers</h3>
<div>[simple-retail-menu id="1" header="none"]</div>
<h3 class="sushi-bar-apps">sushi bar appetizers</h3>
<div>[simple-retail-menu id="2" header="none"]</div>
</div>
Html that works:
<div class="accordion">
<h3 id="zen-shi-apps">zen shi appetizers</h3>
<div>[simple-retail-menu id="1" header="none"]</div>
<h3 id="sushi-bar-apps">sushi bar appetizers</h3>
<div>[simple-retail-menu id="2" header="none"]</div>
</div>
Actually I have also faced that issue long back. Then I tried to dig out the responsible code for the accordion. It was actually of jQuery UI.
The interesting thing is that, in the code they sometimes use the raw id(s) to get that targeted elements. So in this case, they might be collecting the element using id, not by class and that's why it is not working!
So, please check with your accordion-library code and just check whether they are using that way or not.
Cheers!
Related
Alright. So I'm going to try and explain this the best I can. I just don't understand how to use jQuery in HTML and a javascript answer would be most appreciated, but I'll take jQuery if you can give me HTML with it, and not just jQuery code.
I have a guide page, the guide page itself is embedded into the main page using php (index.php?content=guide). On the guide page, I would like to use a show/hide OR a toggle function of sorts to toggle certain parts of the page, as related to the guide. Then, I would like to only show one at a time, as one link is clicked, only show the clicked elements and hide the rest. The list is on the left hand side of the page, while the content to be shown is on the right.
`http://jsfiddle.net/wesman2232/2m2jjcc9/`
(Why isn't toggle working on jsfiddle? It's working fine on my local webserver)
Normally I would just make a different php page for each and every subsection (index.php?content=guide&do=requirements) but I want to try and get away from that, so I'm trying to just get it in one whole page
Currently, it toggles like I want, but I would rather have it all in one script instead of having to write out something like show('news'); show('news2'); hide('updates'); hide('updates2'); etc etc. Also if you just kept clicking on Synopsis it would toggle between the two instead of just switching to that one, and that one only.
I get that this isn't multiple, but for the multiple part is where I have something like this on the media page:
`http://jsfiddle.net/wesman2232/mwnua9q8/`
except I would change it from using id to class and set them all having the same class right?
Guess I need to go back and re-learn everything cause I'm having a hard time wrapping my brain around all this haha. I've tried reading other questions but still can't get it to work the way I want it to.
The problem with your code, in my opinion, is that it is outdated. You are using tables for non tabular design and you are making it difficult for yourself using pure JS in comparison to jQuery.
You need to do the following:
do away with tables and use divs
use the powerful ways of styling your content with CSS3
even though it is very good to know plain JS, use jQuery to make coding fun and easy.
always try to make your HTML as clean as possible with the use of IDs and Classes
This is the way I would redo your code:
$(".link").click(function (e) {
e.preventDefault();
$(".content").removeClass("active");
var content_id = $(this).attr("href");
$(content_id).addClass("active");
});
#wrapper {
text-align: center;
}
#content_container {
margin-top: 10px;
}
.content:not(.active) {
display: none;
}
.title{
font-weight:bold;
text-transform: capitalize;
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="wrapper">
<div>
<a class="link" href="#screenshots">Screenshots</a> |
<a class="link" href="#videos">Videos</a> |
<a class="link" href="#wallpaper">Wallpapers</a>
</div>
<div id="content_container">
<div id="screenshots" class="content active">
<div class="title">Screenshots</div>
<div class="description">Screenshot description</div>
</div>
<div id="videos" class="content">
<div class="title">Videos</div>
<div class="description">Videos description</div>
</div>
<div id="wallpaper" class="content">
<div class="title">Wallpapers</div>
<div class="description">Wallpapers description</div>
</div>
</div>
</div>
Try this.
It's a jquery version.
$().ready(function()
{
$('#gm, #pg').click(function()
{
if($(this).attr("id") == "gm")
{
$("#gameinformation").toggle();
if($("#playguide").is(":visible"))
$("#playguide").toggle();
}
else
{
$("#playguide").toggle();
if($("#gameinformation").is(":visible"))
$("#gameinformation").toggle();
}
});
});
Fiddle : http://jsfiddle.net/2m2jjcc9/2/
ALTERNATE APPROACH :
If you multiple section to toggle, you may use the following. I used an approach to tag each corresponding 'UL' tags of 'a' with an attribute called 'data-dependency' and use it to toggle sections.
$('a').click(function()
{
var $this = $(this).attr('id');
$('a').each(function()
{
var id = $(this).attr('id');
if(id == $this)
{
$("ul[data-dependency='" + id + "']").toggle();
}
else
{
if($("ul[data-dependency='" + id + "']").is(":visible"))
$("ul[data-dependency='" + id + "']").toggle();
}
});
});
Fiddle : http://jsfiddle.net/2m2jjcc9/4/
UPDATED BASED ON REQUIREMENT TO KEEP ALL MENUS OPTIONS OPEN :
$('a').click(function()
{
var $this = $(this).attr('id');
if($("ul[data-dependency='" + $this + "']")[0] != undefined)
$("ul[data-dependency='" + $this + "']").toggle();
else
$(this).closest('li').find('ul').toggle();
});
Fiddle : http://jsfiddle.net/2m2jjcc9/5/
this is a rather complicated request.
So there are three elements to my problem. A JQuery bxslider, a Perch CMS set of taglines that my client must be able to update after website release and a javascript code block.
What I want to be able to do is create a function that replaces the <h2> element with the appropriate tagline (i.e. second product equals item 2 in perch) when the jQuery bxslider changes the image behind it.
So here's the HTML in question
<div class="overlay">
<div class="tagbox">
<h2>We provide business and personal insurance to suit your individual needs</h2>
<a class="read-more">Read more</a>
</div>
</div>
And the standard script for the bxSlider
$('.bxslider').bxSlider({
pager: true,
auto: true,
useCSS: false
// onSlideAfter: /*NEED CHANGING FUNCTION HERE*/
});
And I need a jQuery script that will use the array of taglines which I get using:
<?php perch_content('Taglines');?>
I've tried to do something like this for my function:
$(".tagbox h2").html(/*NEED TO GET ARRAY INDEX HERE i.e. heading 2, 3, 4*/);
I've tried using the $each() function to loop through that comes with jQuery but with no success. Can anyone suggest anything? Really tricky concept and I could do it if my client weren't so dependent on updating content with Perch.
I've had a similar issue with another slider, see this question: In JSSOR, how to access the current caption via Javascript?
In the same Perch template where editors enter the carousel images, you can number content (e.g. by ID) with perch_item_zero_index (starts at 0) or perch_item_index (starts at 1):
<li>
<img src="/images/730_200/tree_root.jpg" />
<div id="caption-slide-<perch:content id="perch_item_zero_index" type="hidden" />"><perch:content type="text" id="caption" label="Text for the tagline" required="true" /></div>
</li>
So the editors will enter these taglines in the same item as the slide image in perch.
As you write, bxslider has a callback for the end of each transition, so that's good. Note that the slider is initialised by assigning it to var slider, so you can access that later:
var slider = $('.bxslider').bxSlider({
onSlideAfter: function(){
// get the text and place it somewhere else
}
});
Now all you need is to know which slide you're in. See http://bxslider.com/options
If you know that, you can fetch your content at the end of each transition and place it somewhere else in the DOM:
var slider = $('.bxslider').bxSlider({
onSlideAfter: function(){
// which slide are we in?
var current = slider.getCurrentSlide();
// get the text from the caption that corresponds to the current slide
// and place it somewhere else in the dom
$(".tagline h2").text($("#caption-slide-" + current).text());
}
});
Untested, but basically, that should be it. Note that there is an issue on https://github.com/stevenwanderski/bxslider-4/issues/604 saying that it might not work yet with "auto".
I have the following code sample:
<div id="dlgTest1" style="display: none">
<p>
Lorem ipsum test popup dialog<br />
<br />
Click the OK button to resume activity.
</p>
</div>
<script type="text/javascript">
$(document).ready(function () {
var myTitle =
"<div style='float: left'>LEFT TEXT</div><div style='float: right'>RIGHT TEXT</div>";
$("#dlgTest1").dialog({
title: '', // new jquery-ui-1.10.2 doesn't allow HTML here
autoOpen: false,
minWidth: 500, width: 500,
minHeight: 200, height: 200,
resizable: true,
modal: true,
show: "blind",
hide: "explode",
buttons: {
"OK": function () {
$(this).dialog("close");
}
}
}).siblings('.ui-dialog-titlebar').html(myTitle); // title goes here
$("#dlgTest1").dialog("open").dialog("moveToTop");
});
</script>
This sample code opens a jQuery dialog, which displays text in the title bar on the left side and on the right side, which is achieved by myTitle, a variable that contains HTML code with two <div> elements.
In previous versions of jQueryUI (e.g. V1.8.20) I was able to directly assign the title attribute with the content of myTitle and it worked like a charm. Now I've upgraded to V1.10.2 and noticed that title doesn't interpret HTML any more but shows the <div> ... in the title instead.
As you can see, I am using the tweak .siblings('.ui-dialog-titlebar').html(myTitle); to pass through my HTML code, which works basically.
But it has the side effect that it hides the (X) button used to close the dialog (that side effect didn't occur in the older jQUery UI version V1.8.20). I can't go back to the earlier version of jQueryUI because I need controls that depend on the latest version.
Question: How can I avoid that the (X) close button is hidden by the right-aligned text?
Note: The icon is displayed, if I use normal text instead of HTML formatted text, so the reason is not that a style or bitmap is missing.
I have already looked everywhere (beginning with http://jqueryui.com/), searched in Google etc. but found no solution.
Any help is much appreciated.
Update: (Answers to the comments below)
I am using the ui-lightness css theme without any modifications
Adding padding-right:20px to the style attribute of the right-aligned div doesn't solve the issue.
Final note:
The discussion with you all helped me a lot solving the issue. I have posted the answer which finally worked for me.
Thank you very much to all who have supported me, you guys are really great! Everyone who has posted an answer got a +1 from me.
The problem is you are replacing the html of the title bar so you are removing the close button.
Change html() to append(), you will need to adjust margins/padding to get it to look right.
var myTitle =
"<div style='float: left'>LEFT TEXT</div><div style='float: right; margin-right:10px;'>RIGHT TEXT</div>";
and
}).siblings('.ui-dialog-titlebar').append(myTitle);
JSFiddle
The approach Epascarello has suggested with .append(myTitle) instead of .html(myTitle) works fine in the JSFiddle example, but unfortunately not with the ui-lightness customization of jQueryUI which I am using.
But the following function does it:
// Insert HTML formatted title in jQuery dialog V1.10.2
// Parameters:
// dialog = reference to jQueryUI dialog,
// hmtlTitle = the title with containing HTML to apply to dialog
function applyHtmlToDialog(dialog, htmlTitle) {
dialog.data("uiDialog")._title = function (title) {
title.html(this.options.title); };
dialog.dialog('option', 'title', htmlTitle);
}
To use it, simply call it the following way:
applyHtmlToDialog($("#dlgTest1").dialog(), myTitle);
or if you prefer to do it in multiple lines:
var myDiag = $("#dlgTest1").dialog(//... your dialog definition ...
);
var myTitle = '<div> ... </div>';
applyHtmlToDialog(myDiag, myTitle);
It will insert myTitle properly and regard the HTML codes contained within.
N.B. (Some background information): This solution was inspired by the following Stackoverflow article:
Icons in jQueryUI dialog title.
I've found out the reason for this behaviour is that the jQuery team had concerns regarding XSS vulnerability of the dialog, so they have changed it on purpose.
You can read more about their discussion here, if you're interested. Hence, the _title is official functionality provided by jQuery in case you want to use HTML codes in the title.
I believe they have chosen an approach which isn't so straightforward, as .dialog({ title: $("... html ...") }), which I personally would have preferred (i.e. using $ to indicate that you want to have HTML in the title).
I have a tweet stream where new tweets are added at the top and the older ones pushed down. You can click on the entire tweet and a panel slides down to reveal, "reply", "retweet", "favorite" etc. The panel is added to each new tweet added in the stream.
The code below works. Shouldn't this be better written so that only one call is being made? Or, as a new tweet is added. would I just have to add to the code with div#tc4, ul#tb4 etc?
$(document).ready(function () {
$("div#tc1").click(function () {
$("ul#tb1").slideToggle("fast");
});
$("div#tc2").click(function () {
$('ul#tb2').slideToggle("fast");
});
$("div#tc3").click(function () {
$('ul#tb3').slideToggle("fast");
});
});
Added Markup:
<div id="tc1" class="tweetcontainer">
<div class="avatarcontainer">
<div class="avatar"></div>
</div>
<div class="content">
<div class="tweetheader">
<div class="name">
<h1>John Drake</h1>
</div>
<div class="tweethandle">
<h2>#Drakejon</h2>
</div>
<div class="tweettime">10m</div>
</div>
<div>
<p>Exceptional Buys Ranger To Give Monitoring Shot In The Arm To Its 'DevOps' Platform http://tcrn.ch/11m3BrO by #sohear </p>
</div>
</div>
</div>
<!-------------Tool Bar -------------------------------->
<ul id="tb1" class="toolbar">
<li><a class="reply" href="#"><span>reply</span></a></li>
<li><a class="retweet" href="#"><span>retweet</span></a></li>
<li><a class="favorite" href="#"><span>favorite</span></a></li>
<li><a class="track" href="#"><span>track</span></a></li>
<li><a class="details" href="#"><span>details</span></a></li>
</ul>
I highly recommend separating your javascript from your detailed page function. The best way to do this is to put the retweeting panel inside the tweet container, then you don't even need to give it an id at all or encode in the javascript information about your html structure and ids. You can then just do:
$('.tweetcontainer').on('click', function(event) {
if ($(event.target).is(':descendantof(.toolbar)')) {
//ignore all clicks within the toolbar itself
return;
}
$(this).find('.toolbar').slideToggle();
});
It's that easy! See it in action in a jsFiddle.
Now you can add as many tweet containers as you want to your page--and your javascript doesn't have to change one bit. Other solutions that require knowledge of specific ids linking to specific ids are suboptimal.
Note the descendantof pseudo-selector is custom (see the fiddle to find out how it works). Also, since you didn't provide any css, I had to choose some--it was quick so don't expect much. (Aww heck I just saw you updated your question to provide a jsFiddle with css giving a far prettier result--but I won't change mine now.) I did have to add a class to the actual tweet itself, but there is probably a better way to style it.
And if you want a click on the displayed toolbar itself (outside of a link) to allow collapsing the toolbar, change the code above to :descendantof(a).
If you don't want to change your page layout, another way to it is to encode the information about the linkage between html parts in the html itself using a data attribute. Change your tweetcontainer div to add a data attribute with a jQuery style selector in it that will properly locate the target:
<div class="tweetcontainer" data-target="#tb1">
You don't really have to remove the id if you use it elsewhere, but I wanted you to see that you don't need it any more. Then on document.ready:
$('.tweetcontainer').click(function () {
$($(this).data('target')).slideToggle('fast');
});
Here is another jsFiddle demonstrating this alternate technique (though it less elegant, in my opinion).
Last, I would like to mention that it seems possible you have a little bit of "div-itis". (We have all been there.) The toolbar anchor elements have unnecessary spans inside of them. The tweet name h1 element is inside a div, but could just be an h1 with class="name" instead.
In general, if there is only a single item inside a div and you can change your stylesheet to eliminate the div, then the div isn't needed. There are an awful lot of nested divs in your html, and I encourage you to remove as many of them as you can. Apply style to the other block elements you use and at least some, if not many, won't be needed.
I'd suggest (though currently untested):
$('div[id^="tc"]').click(function(){
var num = parseInt(this.id.replace(/\D+/g,''),10);
$('#tb' + num).slideToggle("fast");
});
Though given that you don't need the num to be a number (it'd be fine as a string), you could safely omit the parseInt().
Yes, you can write this code much more compactly like this:
$(document).ready(function() {
for (var i = 1; i < 3; i++) {
$("div#tc" + i).click(function() { $("ul#tb" + i).slideToggle("fast"); } );
}
});
I would like to remove a div from the TinyMCE editor content that has a specific class.
In the ideal world I'd like to be able to do this via the valid_elements option but I don't know if it's achievable.
Here is a sample of editor content:
<div class="content">
Some html content here
<div class="anotherclass"></div>
</div>
I would like the
<div class="content">
stripping out so the editor will only show this:
Some html content here
<div class="anotherclass"></div>
Cheers guys.
First get the innerHTML of the div, and then append that content to the div, after which you can remove it.
In jQuery:
var contentHtml = $(".content").html();
$(".content").after(contentHtml);
$(".content").remove();
Of course, if you have multiple divs with these classes its more complicated because then you would have to work with parents etc.
Problem here will that by default your editor will have a root_block element (in your case div) and all content gets wrapped inside that kind of root_block element. This is done for styling purposes, but can be deactivated using this initialization params
force_p_newlines : false,
force_br_newlines : false,
convert_newlines_to_brs : false,
remove_linebreaks : true,
Once that is done you can use this code to easily get rid tof your divs.
var $elements_to_be_removed = $(".content");
$elements_to_be_removed.each(function(index) {
$(this).replaceWith(this.innerHTML);
});