Jquery with Sitecore Page editor - javascript

I need to put span tags around first word in a line. I used the below Jquery which is working fine in sitecore standard mode.
$("body").has(".widget h2").addClass("standard-mode");
$("body").has(".scLoadingIndicatorInner").removeClass("standard-mode").addClass("page-edit");
$('.standard-mode .widget h2').html(function(i, html){
return html.replace(/(\w+\s)/, '<span>$1</span>')
})
When i first load the page editor this works fine as well(by not inserting the span tags), but when i created a multivariate test switching between the A/B by using arrow marks shows like inserting the span tags which it should not suppose to do as it is in page-edit mode but it does and breaking the html as below.
<h2>
<<span>input </span>id="fld_D26C954B73BE4C62B6F25BE191A86F18_7B55B5E5EDD84D4E88B16C6E073495A5_en_1_0e80a9c63ab6419f8135b70511e892f1_16487" class="scFieldValue" name="fld_D26C954B73BE4C62B6F25BE191A86F18_7B55B5E5EDD84D4E88B16C6E073495A5_en_1_0e80a9c63ab6419f8135b70511e892f1_16487" type="hidden" value="Badger Cull"><span class="scChromeData">{"commands":[{"click":"chrome:common:edititem({command:\"webedit:open\"})","header":"Edit the related item","icon":"/temp/IconCache/SoftwareV2/16x16/cubes_blue.png","disabledIcon":"/temp/cubes_blue_disabled16x16.png","isDivider":false,"tooltip":"Edit this item in the Content Editor.","type":"common"},{"click":"chrome:rendering:personalize({command:\"webedit:personalize\"})","header":"Personalize","icon":"/temp/IconCache/PeopleV2/16x16/users3_edit.png","disabledIcon":"/temp/users3_edit_disabled16x16.png","isDivider":false,"tooltip":"Personalize component.","type":"sticky"},{"click":"javascript:Sitecore.PageModes.PageEditor.postRequest('ActiveISPageEditor:publish(id={D26C954B-73BE-4C62-B6F2-5BE191A86F18})',null,false)","header":"Publish the related item","icon":"/temp/IconCache/Network/16x16/download.png","disabledIcon":"/temp/download_disabled16x16.png","isDivider":false,"tooltip":"Publish this item.","type":"common"},{"click":"chrome:rendering:editvariations({command:\"webedit:editvariations\"})","header":"Edit variations","icon":"/temp/IconCache/SoftwareV2/16x16/breakpoints.png","disabledIcon":"/temp/breakpoints_disabled16x16.png","isDivider":false,"tooltip":"Edit the variations.","type":"sticky"}],"contextItemUri":"sitecore://master/{D26C954B-73BE-4C62-B6F2-5BE191A86F18}?lang=en&ver=1","custom":{},"displayName":"Header Text","expandedDisplayName":null}</span><span scfieldtype="single-line text" sc_parameters="prevent-line-break=true" contenteditable="false" class="scWebEditInput scEnabledChrome" id="fld_D26C954B73BE4C62B6F25BE191A86F18_7B55B5E5EDD84D4E88B16C6E073495A5_en_1_0e80a9c63ab6419f8135b70511e892f1_16487_edit" sc-part-of="field">Badger Cull</span>
</h2>
Any suggestions will be helpful.

You can check the JavaScript property Sitecore.PageModes.PageEditor to see if you are in page editor mode and can disable your javascript accordingly.
function isPageEditor() {
if (typeof Sitecore == "undefined") {
return false;
}
if (typeof Sitecore.PageModes == "undefined" || Sitecore.PageModes == null) {
return false;
}
return Sitecore.PageModes.PageEditor != null;
}
if (isPageEditor() == false) {
//do your stuff here
}

Related

TinyMCE - Button to wrap selection not selecting surrounding tags

In WordPress I have added a custom editor button to get the contents of a selection and wrap it in a shortcode. The content is not getting the tags surrounding the selection.
For example:
<h1>Heading text</h1>
becomes
<h1>[shortcode]Heading Text[/shortcode]</h1>
Not
[shortcode]<h1>Heading Text</h1>[/shortcode]
It does work for
<h1>Header</h1>
<h2>Sub-Header</h2>
becomes
[shortcode]<h1>Header</h1>
<h2>Sub-Header</h2>[/shortcode]
This is the code I have.
(function() {
tinymce.create('tinymce.plugins.zgwd', {
init : function(ed, url) {
ed.addButton('headerblock', {
title : 'Add a Header Block',
cmd: 'headerblock',
});
ed.addCommand('headerblock', function() {
var selected_text = ed.selection.getContent({ format: 'html' });
var return_text = '';
if( !(selected_text && selected_text.length > 0) ) {
selected_text = 'Add header block text here';
}
return_text = '[header-block]' + selected_text + '[/header-block]';
ed.execCommand('mceInsertContent', 0, return_text);
});
},
createControl : function(n, cm) {
return null;
},
});
tinymce.PluginManager.add('zgwd', tinymce.plugins.zgwd);
})();
How can I get the content including the <h1> tags (or similar). Am I using the wrong function to get the content or is there a setting I am missing somewhere? I tried .getnode() but get the same result.
If you want to do something with a single block tag, getNode is your best bet. If you look at this Fiddle with the console open in Dev Tools, try selecting one line, and then try selecting both. getNode() and getContent() behave a little differently based on selection.
getNode() Returns the selected element, but, if you have more than one element selected, it returns the common ancestor (in this case body).
getSelection() will return tags if you select multiple blocks, which is why it works when trying to surround more than one block tag.

GTM is not registering Click URL from Image,

Iam stuck with the code. The javascript variable Retimgexp is returning as "", Not sure why. It only returns "undefined" when I click on the body of the page.
Basically what I am trying to achieve is when user clicks on image i wanted to grab the href of the parent "a" element and push it ultimately to the GA TAG using variables, so i have made modifications to the code.
can you please have a look.
Custom javascript File name:- Find closest
function() {
return function(target, selector) {
while (!target.matches(selector) && !target.matches('body')) {
target = target.parentElement;
}
return target.matches(selector) ? target : undefined;
}
}
Custom javascript File name:- Retimgexp
function() {
var el = {{Find closest}}({{Click Element}}, 'a[href^="http"]');
return typeof el !== 'undefined' ? el.id : undefined;
}
Basically this is the HTML code
<div class="card__media-overlapping__media">
<a href="https://capgemini.aws.hmn.md/experts/it-strategy-and-transformation/yvette-zzauer/">
<img src="https://eu-west-1.tchyn.io/capgemini-dev/uploads/2017/07/yvette_zzauer.jpg?resize=324,197" alt="Yvette Zzauer">
</a>
</div>
Its Working now
I was referencing the ID which was wrong should have referenced "href". Its working now.
function() {
var el = {{Find closest}}({{Click Element}}, 'a[href^="http"]');
return typeof el !== 'undefined' ? el.href : undefined;
}
Oki one of the simplest way could be a one liner, then you can check for the fallback condition etc
{{Click Element}}.parentNode.getAttribute("href");

Changing html content using if statement and jquery

i'm trying to display certain sentences and images according to the value of a select menu.
If an user selects that his platform is "Android", then he'll see an specifc message. If he selects that his platform is "iOS", then he will see another.
I want to achieve this using a variable "isAndroid", if it is true it will display the Android message plus the android icon and if it is false it will display the iOS message and the iOS icon.
Then i implemented the jquery method "change()" to being able to swtich and change the content whenever the selector value is changed between "Android" and "iOS". I've managed to achieve my objective in a different and more complicated way, but i want to do it with this boolean to use it on more stuff later, if "isAndroid" is true it will do many other things, but i'm showing the basic here to keep it simple.
This is my actual HTML and Javascript code:
function platformAndroid() { //function with the content of Android. it should run if "esAndroid" is true
$("#iconoDispositivo").attr("src","http://i.imgur.com/ksYWdrF.png");
$("#chosenPlatform").html("Your chosen platform was android");
}
function platformIos(){ //function with the content of iOS. it should run if "esAndroid" is false
$("#iconoDispositivo").attr("src","http://i.imgur.com/YPqQsib.png");
$("#chosenPlatform").html("Your chosen platform was iOS")
}
var isAndroid = true;
function dispositivoStart(){ // this functions displays the correct stuff when user refresh the page
if($('#dispositivo').val() === "Android"){ //if my select input value is android, then "esAndroid" is true
isAndroid;
} else {
isAndroid = false; // otherwise it is false
}
$('#dispositivo')on.("change",function(){ //here i wrote this piece of code to switch "esAndroid" to true or false when they select different values on the selector input
if($(this).val() === "Android"){
isAndroid;
} else {
isAndroid = false;
}
})
if(isAndroid){ // here is the piece of code that displays the content. if esAndroid is true, then the function that displays "Android" content runs.
platformAndroid()
} else {
platformIos() //if "esAndroid" is false, then the function that displays "iOS" content runs
}
}
dispositivoStart();
#chosenPlatform {
font-size: 20px;
color: green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Platform choose
</title>
</head>
<body>
<h2>Platform</h2>
<div class="field">
<label for="dispositivo">Choose your platform</label><br>
<select id="dispositivo">
<option>Android</option>
<option>iOS</option>
</select>
</div>
<div class="field">
<p id="chosenPlatform">Your chosen platform was Android</p> <img src="http://i.imgur.com/ksYWdrF.png" width="32" alt="androidIcon" id="iconoDispositivo">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js"></script>
</body>
</html>
I can't understand why in the snippet i can't call jquery correctly, in my own files i use cdns, but that's the code that i'm trying to run.
With the current code, the boolean from "isAndroid" changes to false, but doesn't display the content that it should display when "isAndroid" is false (the iOS content). It also doensn't switch back to true when the select input value switchs to "Android" again.
As i said at the beggining, i could achieve my objetive if i use
#dispositivo.val() === "Android"
but i think that doing "isAndroid" = true/false is simpler, becouse later on i have to keep using that boolean to display certain content depending on that selector value.
I hope i was clear enough, this is my second question written on Stackoverflow, thanks in advance.
Before we address your primary issue, we should address your HTML. Run the HTML through a validator (not W3C, it's outdated). The demo features a working example of HTML content being inserted into a <section> and values being set in an <output> form control, which is determined by a user's selection of a <select>.
Methods, Properties & Processes
jQuery
.on() Event Delegation
.html(), .text(), & .val()
JavaScript
ES6 Template Literals
switch()
Details are commented in demo
Demo
/* NOTE: ES6 Template Literals are being used instead of
|| String Literals:
[Example: String Literal >>>
var SL = "This is a String, this is a " + variable\
+ " concatenated";
[Example: Template Literal >>>
var TL = `This is a String, this is a ${variable}
interpolated`;
*/
/* Register change event on the select#mobile
|| .on() method delegates events. Main advantage
|| of delegating events is that the event will
|| be registered not only for elements currently
|| in DOM, but elements that will be there in the
|| future.
*/
/* Callback function is getContent which is invoked
|| upon a change event occurring on #mobile
*/
$('#mobile').on('change', getContent);
function getContent(e) {
// Store the value of a form control (i.e. #mobile)
var opt = this.value;
/* Pass value to a switch(). A switch() method is
|| a if/if else condition that's easier to read.
*/
switch (opt) {
// if (opt === 'android') {...
case 'android':
/* If getting/setting data of a form control
|| use .val() method.
|| ex. input, output, select, etc..
*/
// Change the value of output#out
$('#out').val(`Selected OS is Android`);
/* If getting/setting content between an element's
|| tags use .html() or .text() methods
|| ex. <div>CONTENT</div>
*/
// Change the HTML of section.dock
$('.dock').html(
`<h1>Samsung Galaxy</h1>
<label>Model: <input></label>
<button>DONE</button>`);
break;
case 'iOS':
$('#out').val(`Selected OS is iOS`);
$('.dock').html(
`<h1>iPhone</h1>
<label>Model: <input></label>
<button>DONE</button>`);
break;
/* If its neither 'android' nor 'iOS', then it
|| refers to default case. In this particular case
|| output#out and section.dock will be erased.
*/
default:
$('#out').val('');
$('.dock').html('');
break;
}
}
select,
input,
button,
label {
font: inherit
}
<form id='interface'>
<select id='mobile'>
<option value='-'>-------------</option>
<option value='android'>Android</option>
<option value='iOS'>iOS</option>
</select>
<output id='out'></output>
</form>
<section class='dock'></section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Append div only if it does not contain text JQuery

I am creating a social media website and am trying to make a comment textarea appear when users click on a status.
Here is what I have so far:
$(".status").click(function (){
//Check if status div they clicked on contains a textarea already
if($(this).closest('div').innerHTML.indexOf("<textarea name='status_body'>") == -1) {
//Append with textarea
var textarea = "<textarea name='status_body'></textarea>";
$(this).closest('div').append(textarea);
}
});
This was working before I put the if statement in. Of course without the if statement a textarea will be added everytime the user clicks. I would only like for a textarea to appear if there is not one aready.
Another method I tried and failed with is:
if(!$(this).closest('div:contains("<textarea")').length > 0)
You're close, just check for the existence with .length
if ($(this).closest("div").find("textarea").length > 0) {
//contains a text area!
} else {
//Doesnt!
}
Do not search for it as text. You should threat the textarea for what it is, a DOM element.
if($(this).closest('div').find("textarea[name='status_body']").length == 0) {
/*...*/
}

MVC 4 using jquery how to check if the model property has elements in it

I'm passing in a view model that works with the CheckBoxListFor property and I would like to hide the checkbox section if when I repost to the page there are no check marks ticked. I can show and hide the check box section with no problem using:
$('div.KSearch').hide();
or
$('div.KSearch').show();
What I've been trying to do is check the view model which has a List which hold the information for the keyword model. Is there anyway to check if this list has element being passed in within jquery so that I can show or hide the section with something like:
if (('#Model.SelectedKeywords').length) {
$('div.KSearch').show();
} else {
$('div.KSearch').hide();
}
but this always shows the section. Any ideas?
Something like this?
var len = #Model.SelectedKeywords.Count;
if (len > 0) {
$('div.KSearch').show();
} else {
$('div.KSearch').hide();
}
('#Model.SelectedKeywords').length is treated as a string length in javascript, and it's always positive (and true) ;)
Check MVC Model is null or not in jquery
<script type="text/javascript">
var checkBoxCount = #(Model.SelectedKeywords != null ? Model.SelectedKeywords.Count : 0);
if (checkBoxCount != 0) {
$('div.KSearch').show();
} else {
$('div.KSearch').hide();
}
</script>
I hope this will help.

Categories