WooCommerce double load - javascript

I have this Wordpress project and I am using WooCommerce Plug-in and WooCommerce Adamas Theme. I have the following problem:
I need to replace the word "Cart" from the top right menu with an icon of a cart as part of my project. What my theme does in its functions.php file is to create two a links to the Cart's contents PoP Up element. The first is the word "Cart" and the second is the cart product counter.
What I have tried is to add the following CSS properties by adding the class cmagnet-cart to the second, in order to include the cart icon.
.cmagnet-cart{
background: url('http://www.athlokinisi.gr/images/shopping-cart.png') no-repeat 10px 6px;
min-width: 45px;
text-align: right;
background-size: auto 17px;
}
I have added the class to the appropriate element at the functions.php cartShow() function where it is originally generated. As you can see, the problem is that when page loads, it shows the icon perfectly on position and then there is a javascript reload of some WooCommerce parameters and hides it again, by returning to its original values. Thus, without my added class.
After contacting the Adamas Theme Support team at PremiumCoding and after several tickets which took place for over 2 weeks, it was pointed out to me that I need to make an alteration at WooCommerce's JS function, perhaps the cart-fragment.js. The problem is that nothing makes sense to me in there and I really cannot find where to make the code alteration in order for the Javascript's second load to include my function or exclude this element from double loading. The Suport team there couldn't assist me further.
I would appreciate endlessly any help as well as an explanation of why this happens. It doesn't make any sense to me why to load some elements two times.
To add two additional information:
- I know that when I fix the issue I will just hide (probably by putting in comments) the first a link which prints the word "Cart"
- The last response I got from support was the following (in case it is of any help):
even if you replace text with icon after loading WooCommerce Ajax,
text will be back. So you will need to change WooCommerce js function
or translate all WooCommerce plugin and theme with WPML plugin and
string translation module.
Extended info:
In general it's not enough for me to just replace the first a link that says "Cart" with the cart's image, because it doesn't solve my bigger problem which includes the following: I am using Greek language for this project and the theme has many uppercase CSS elements. There are some problems with this because Greek words in uppercase cannot be automatically transformed because you have to remove the accents from the vowels. Therefore, I had made a jQuery functions which runs on document ready and corrects this problem, but due to the aforementioned problem of the double load it returns all text back to the previous state.

I solved it by adding this code:
//Uppercase correction for Greek language
String.prototype.replaceArray = function(find, replace){
var replaceString = this;
for (var i = 0; i < find.length; i++){
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
var e = jQuery('a, h2, h3, button, li'), l = e.length, i;
if (typeof getComputedStyle == "undefined"){
getComputedStyle = function(e) {return e.currentStyle;};
}
for (i=0; i<l; i++){
if (getComputedStyle(e[i]).textTransform == "uppercase"){
var find = ['ά', 'έ', 'ί', 'ή', 'ύ', 'ό', 'ώ'];
var replace = ['α', 'ε', 'ι', 'η', 'υ', 'ο', 'ω'];
var replaceTo = e[i].innerHTML;
replaceTo = replaceTo.replaceArray(find, replace);
e[i].innerHTML = replaceTo;
}
}
//Uppercase correction for Greek language
into the file:
wp-content/plugins/woocommerce/assets/js/frontend/cart-fragments.min.js
This JS file was the one responsible for the double load of contents. It may not be the best solution, yet a working one.

Related

Parse a JS array and add a style for matching values using .addClass()

I'm confused as I don't believe I've done anything out of the ordinary here, that I haven't done before.
I'm looking to implement a feature similar to Excel's "Highlight Duplicate Values" action.
I have a function that takes tab separated values and parses them into a list of claims. It's all hacky, but the "list" (or table) is a series of divs that contains various elements such as a button that holds the claim ID. Once the list is created and all claims are visible, I parse it to find what buttons hold duplicate values, and apply a class to said button to highlight it using .addClass().
The problem is that I cannot seem to get the button to highlight. Now I've used functions like this before without any issue, including making a row highlight when clicked (and dim the others), and so on, but I'm confused what seems to be wrong here.
The parsing code is as follows:
function parseForDuplicates() { // Look for duplicates to highlight
var importedListLength = $("div.column.colClaim").length; // Get length of claims in list
var claimsToReview = []; // create an array for below...
for (let a=0; a < softParsedList.length; a++) { // Add the claim IDs to the claimsToReview array
claimsToReview.push(softParsedList[a][0]);
}
for (let i=0; i < importedListLength; i++) { // Compare values...
var currentCheckedClaimBtn = $(`div.column.colClaim:nth-child(${i+1}) button`); // Get the button element for current line
if (i > 0) {
var previousCheckedClaimBtn = $(`div.column.colClaim:nth-child(${i}) button`); // Get the button element for previous line only if we're further along the list
} else {
var previousCheckedClaimBtn = "none"; // set to "none" if we're at the beginning.
}
if (i < importedListLength) {
var nextCheckedClaimBtn = $(`div.column.colClaim:nth-child(${i+2}) button`); // Get button element from next line
} else if (i == importedListLength) {
var nextCheckedClaimBtn = "none"; // set to "none" if we're at the end
}
var currentCheckedClaim = $(`div.column.colClaim:nth-child(${i+1}) button`).val(); // Get claim ID from current line
if (i > 0) {
var previousCheckedClaim = $(`div.column.colClaim:nth-child(${i}) button`).val(); // Get claim ID from previous line
} else {
var previousCheckedClaim = "none"; // set to "none" if we're at the beginning
}
if (i < importedListLength) {
var nextCheckedClaim = $(`div.column.colClaim:nth-child(${i+2}) button`).val(); // Get claim ID from next line
} else if (i == importedListLength) {
var nextCheckedClaim = "none"; // set to "none" if we're at the end
}
//console.log(`Previous Claim: ${previousCheckedClaim}`);
//console.log(`Current Claim: ${currentCheckedClaim}`);
//console.log(`Next Claim: ${nextCheckedClaim}`);
if (currentCheckedClaim == nextCheckedClaim) { // If the current claim matches next claim
currentCheckedClaimBtn.addClass('duplicateClaim'); // Highlight current button
nextCheckedClaimBtn.addClass('duplicateClaim'); // Highlight next button
nextCheckedClaimBtn.addClass('duplicateClaim'); // Highlight next button
console.log(`${currentCheckedClaim} is a duplicate!`);
}
if (currentCheckedClaim == previousCheckedClaim) { // If the current claim matches previous claim
currentCheckedClaimBtn.addClass('duplicateClaim'); // Highlight current button
previousCheckedClaimBtn.addClass('duplicateClaim'); // Highlight previous button
console.log(`${currentCheckedClaim} is a duplicate!`);
}
}
}
The CSS in question...
.duplicateClaim {
border-color: #BB9955 !important;
background-color: #773311 !important;
color: #FFFFFF !important;
}
I've tried with and without !important and that doesn't change anything
When I open up DevTools I can see that the styles get applied appropriately, however in the Styles sidebar, the style is nowhere to be found! I can add it manually to the stylesheet, and at that point, the buttons highlight as intended!
I've gone over the seemingly trivial things: I've definitely saved the CSS file. The HTML file points to the correct CSS file (it never changed to begin with), and there are no conflicting styles that I'm aware of. I use two stylesheets (one named style2.css and the other named external.css and there are no conflicts between them. I tried disabling external.css - no change. I also made sure I didn't somehow open the wrong css (from production or a backup) and just have been editing CSS that was never referenced by changing a DIFFERENT rule - the body - to have a background color that's #FFFFFF and it works. I've also tried inserting it directly into the HTML... that doesn't work. Moving .duplicateClaim to the TOP of the CSS file? Nope. Maybe I just fat fingered it all? Nope. Spelling is correct. I did a copy/paste just in case my eyes have betrayed my brain - nah, they're still cooperating with me... for now. And what about adding a class that's actually an ID?
Yeah, no, that period has not magically turned into a hash. Most definitely has remained a period, and hasn't given me an issue. Oh oh! But what about applying the style DIRECTLY too the element? Nah, I assure you I've tried and nothing wants to play nice.
And lastly, I've tried generating each line WITH the class already entered! That doesn't work either. For whatever reason, chrome just seems to eat that one rule for lunch, and it just doesn't exist. I feel like there is SOMETHING dumb that I'm just not looking at and I'm just dealing with being really, really tired, but I need some kind of sanity check here. Or, maybe I really am going crazy...
Of course, again, let me emphasize that when looking at the source in the developer tools, the class most definitely gets added to the elements that I specify in the code - the JS appears to work, regardless of whether or not it's messy and triggers you (however it's not the first time something appears to work but is still wrong. It just seems like the class ceases to exist the moment the page is loaded. And if I manually add it in the developer tools by clicking the New Style Rule button (the plus next to the :hov and .cls buttons)? It applies to the correct buttons without issue.

Squarespace - How to display description/custom text on index thumbnail on hover

Basically, I want to be able to show title and some text on hover on all my index thumbnail like this website.
http://www.timboelaars.nl/
However, in the current squarespace template that I am using (I believe it's called York), the markup is only grabbing the page title and therefore displaying the page title on hover. (See the below code block, you can see the page title in there, that's the only thing that the template displays on Hover)
<div class="index-item-text-wrapper">
<h2 class="index-item-title">
<a class="index-item-title-link" href="/google-shopping/" data-ajax-loader="ajax-loader-binded"><span class="index-item-title-text">**PAGE TITLE**</span></a>
</h2>
</div>
There's no field for me to put any HTML so I am seeking help to use javascript to manually inject custom HTML markup to every single thumbnail, then show them on hover.
TL;DR I want to be able to display more than just the title on hover (ideally my own HTML markup so I can customize the style) on my thumbnails but that's not supported by the template.
Here is my website http://shensamuel.com/
I am really weak at Javascript and I've searched for a solution for this problem for quite long. Any help will be much appreciated!
Thanks!
The following Javascript can be used to insert text for each tile on the page. The code would be inserted using the footer code injection area (unless you're using Developer Mode in which case you'd insert it with the rest of your scripts).
<script>
(function() {
var tiles = document.getElementsByClassName('index-section');
var thisTile;
var titleText;
var description;
var parent;
var i, I;
for (i=0, I=tiles.length; i<I; i++) {
thisTile = tiles[i];
titleText = thisTile.getElementsByClassName('index-item-title-text')[0];
parent = thisTile.getElementsByClassName('index-item-text-wrapper')[0];
description = document.createElement('span');
description.className = 'index-item-description-text';
switch(titleText.innerHTML.toLowerCase()) {
case "google shopping":
description.innerHTML = "Some custom text.";
break;
case "hana":
description.innerHTML = "More text that's custom.";
break;
case "wali":
description.innerHTML = "Custom text here.";
break;
case "cypress":
description.innerHTML = "Type anything you want.";
break;
case "ryde":
description.innerHTML = "Just another bit of text.";
break;
default:
description.innerHTML = "";
}
parent.appendChild(description);
}
})();
</script>
Observe the pattern in the code in order to add new tiles or edit existing ones. You will see that the script attempts to match (a lower case version of) the 'title' text and then inserts text based on each title. This allows you to add more in the future by repeating this 'case' pattern. Of course if you ever change the title of a tile you'd have to correspondingly change this Javascript code.
You can then style the description by inserting CSS via the Squarespace CSS Editor (or via your base.less file if using Developer Mode). For example:
.index-item-description-text {
display: block;
font-size: 1.2em;
color: #FFFFFF
}
Note that while there is an alternative method that would use each tile's respective URL to do an AJAX query and obtain meta data about each project (and therefore allow you to use the Squarespace content manager to insert this 'description'), that method seems unnecessarily complex for your case.
Update 8/17/2016: Regarding AJAX and how to disable AJAX loader in Squarespace: Jason Barone has suggested adding this snippet to your Code Injection > Footer to disable the "AJAX" pageloader. He noted that it will disable the smooth, AJAX transitions between pages, but will allow custom Javascript like usual.
<script>
//Credit: Jason Barone, http://jasonbarone.com/
window.Template.Constants.AJAXLOADER = false;
</script>
Also, some templates have an option to disable AJAX within the style editor (image credit: SSSUPERS):
Update 9/28/2016:
It has been reported that the code provided above no longer disable AJAX. However, some newer templates have added an 'Enable AJAX Loading' setting that can be toggled off.

Display category name inside image with Javascript

I'm using Magazine Pro Child Theme for the Genesis Framework. This theme displays the Entry Date inside the featured images at the home page. As far as I know (not a programmer) it uses an apparently simple javascript code to do so:
jQuery(function( $ ){
// add js body class
$('body').addClass('js');
// find time for each entry and move it inside the image link
$('.home-middle article, .home-top article').each(function(){
var $time = $(this).find('.entry-time');
$(this).find('a.alignleft, a.alignnone, a.alignright').append($time);
});
I would like to replace the Entry Date for the Entry Category of each post. Is it possible just customizing the Javascript file?
Thank you for your help.
Do you mean replace A with B by saying replace A for B? If so, the following should do that.
The only changed part is the code block added to the middle of the each's function.
Note: I guess you want to replace the red tooltips in both the top and middle widget area, the following code only does the middle part because I can't find the category for the top featured article on the page(as you can see, the if statement ensures only middle ones are filled with category). Also, new texts filling the red tooltips should be Leadercaptalized, change the line between {} to $time.text($widgetArea.find('.widget-title').text().toUpperCase()); if you want wholly captalized ones, or toLowerCase for lowercased ones.
jQuery(function( $ ){
// add js body class
$('body').addClass('js');
// find time for each entry and move it inside the image link
$('.home-middle article, .home-top article').each(function(){
var $time = $(this).find('.entry-time');
var $widgetArea = $time.parents('.home-middle, .home-top');
if($widgetArea.hasClass('home-middle')) {
$time.text($widgetArea.find('.widget-title').text());
}
$(this).find('a.alignleft, a.alignnone, a.alignright').append($time);
});

changing cssRules with javascript is not permanent on client, getting wiped out after partial post back

I generated some css from database values on Page_Load and Then wrapped it like-
CssDiv.InnerHtml = "<style id=\"main_styles\" type=\"text/css\">\n" + {Css as string} + "\n</style>"
here CssDiv is like-
<div id="CssDiv" runat="server"></div>
user are allowed to change these css values with color pickers and drop downs. on change of picker or dropdown, I am making ajax call with the selected value to server, saving it into database. Now on success of this request, I have to change the content of $("style#main_styles") according to user's selection.
The problem is
1) When I am changing the Css its being reflected on the page but not under developer tool (that open when you right click to Inspect element). For example assume following css-
#zoneBody .blocktextContent {
background-color: #99daee;
}
now user selected #1066cc from the picker, when my code runs #1066cc is being applied on the element "#zoneBody .blocktextContent" on page but when I am inspecting the element in the developer console its still showing-
#zoneBody .blocktextContent {
background-color: #99daee; // while it should be- "background-color: #1066cc;"
}
2) The changes I made are not permanent on browser, i.e. when any other element on Page is causing partial post-back, although I am not touching CssDiv on server yet its resetting the users selection.
(I have an update panel, that wraps complete page content, even CssDiv... This is causing partial post-backs).
I am using following code to apply the user's selection-
var layoutelement= "#zoneBody .blocktextContent";
var style = "background-color";
var stylevalue= "#1066cc"; // user's selection
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
var sheet = sheets[i];
if (sheet.ownerNode.id == "main_styles") {
var rules = sheet.cssRules;
for (var j = 0; j < rules.length; j++) {
var rule = rules[j];
if (rule.selectorText == layoutelement) {
rule.style.setProperty(style, stylevalue);
// I also tried "rule.style[style] = stylevalue;"
break;
}
}
break;
}
}
I can not use-
$(layoutelement).css(style, stylevalue);
because layoutelement can be more complex like-
layoutelement = "#zoneBody .blockTextContent a,#zoneBody .blockTextContent a:link,#zoneBody .blockTextContent a:visited,#zoneBody .blockTextContent a .yshortcuts";
I hope I am clear enough, but if you need any more description.. let me know in comments.. Thank you
Instead of changing the values of the styles, why not write the styles down in advance, and just toggle the element's classes? You can use jQuery addClass, removeClass and toggleClass if you want. Much more practical than fiddling with the CSS style definitions themselves.
For problem 1, the issue is probably that the developer tool (or view within the developer tool) you are using does not show applied styles, but simply the rules in the style sheet that match that element based on the selector. Or, in other words, it only shows the css rules in the style sheet that apply to the element you are inspecting. To see the styles that are applied at a given time, you will need to examine the styles by inspecting the element in the DOM or use javascript and the CSSStyleDeclaration object returned by getComputedStyle.

How to link to highlighted text on another page

I have a static HTML page where I am using span tags and javascript to highlight selected portions of text. On a separate page, I would like to link back to this HTML page and have specified highlighting active. See provided code below.
The issue is the required style="background: transparent" tag. It has to be there so that the highlight is only active when clicked upon, but this also means that when I attempt to link to this page as specified below, the highlight is not active.
Any help would be much appreciated. Thanks.
Clicking this link highlights specified portions of text in the document.
<span title="Warscape"><a title="Warscape" onclick="highlightSpan(this.getAttribute('title'))" href="">Warscape</a></span>
This is the text that is highlighted when clicked.
<span title="Warscape" class="highlight" style="background: transparent">During this month while we have been building Fort No 1 Spring field Missouri, quite a No of Regiments have arrived from the north & now the Army of the Frontier [is?] formed</span>
Code to link to page with highlighting.
<a href="j_62sept.html?highlight=Warscape">
CSS re. highlighting
.highlight {background:#bcdbda;}
Javascript re. highlighting
function highlightSpan(spanTitle)
{
var spans = document.getElementsByTagName("span");
// take away color
for (var i = 0; i < spans.length; ++i)
{
spans[i].style.backgroundColor = "transparent";
}
// add color
for (var i = 0; i < spans.length; ++i)
{
if (spans[i].getAttribute('title') == spanTitle)
{
spans[i].style.backgroundColor = "#bcdbda";
}
}
}
I recognise that this is an old thread, but this problem can now be addressed for Chrome using the Scroll to Text Fragment feature described here:
https://chromestatus.com/feature/4733392803332096
In short, it allows you to provide a link which jumps to a specific string of text and (in Chrome's implementation) highlights that section. A basic version of the link would look like this:
https://en.wikipedia.org/wiki/Cat#:~:text=Felis%20catus
when your clicking the links to the page where the highlighting takes action (<a href="j_62sept.html?highlight=Warscape">
) you need to somehow read querystring value on that page to highlight the right span. You can use javascript for this. See this example: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
This is an interesting question. If you'd like to have the javascript pick up on parameters in the url, you can use the window.location.href parameter to pull it out. So, quite simply the following function:
function CheckForHighlight(){
href = window.location.href;
values = href.split('?')[1] // Remove the url
highlight = values.split('=')[1]; // Grab the second parmeter
highlightSpan(highlight); // Highlight it!
}
Please Note that this is a very basic example. I encourage learning through simplicity, and this function can be expanded to dynamically parse all url varaibles. Brain Exersise for you!

Categories

Resources