Toggle Visibility of an Uncontrollable Element in React - javascript

I have Hubspot chat script embedded in the index.html file of my React App using the <script/> tag for user communication.
Now, when a button is clicked I want the hubspot container to be hidden and then when another button is clicked I want it to be displayed again.
I do not have control over the behaviour of the chat icon because it was added to the page via a <script/> tag.
But after some digging I was able to get the id of the element so here is how I've tried toggling the visibility of the chat but it's not working for me.
const toggleHubspotContainer = (turnOn) => {
let hubSpotContainer = document.getElementById("hubspot-messages-iframe-container");
if (turnOn) {
hubSpotContainer.style.display = 'block';
return;
}
hubSpotContainer.style.display = 'none'; //The chat icon is not hiding even after this
}
Please note that the hubspot script was added in the index.html file like this
<script type="text/javascript" id="hs-script-loader" async defer src="//js-eu1.hs-scripts.com/adadadad.js"></script>
Is there a way to do this properly?
Thank you.

Try this, consider your script is in header
function hideHb() {
var head = document.getElementsByTagName('head').item(0);
var js = document.getElementById("hs-script-loader");
head.parentNode.removeChild(js);
}

Related

Hiding a div container including php generated content with a script

I'm currently working on a website which has a search engine including advanced search options with filters. I want to hide the filters until a category has been chosen. I'm not sure if that script would even work within the php file, because I also tried the script with simple alerts but it didn't work. I positioned this script at the end of the php file of the advanced search options.
<script>
if (document.getElementById("main_cat").value == "-1")
{
document.getElementById("custom_fields").style.display = "none";
}
else
{
document.getElementById("custom_fields").style.display = "inline";
}
</script>
custom_fields is the id of a div container which displays all the filters with php generated content. main_cat is the id of the category, if the value is -1, no category is chosen.
I'm working on a website with wordpress if that is important to know.
Thanks for your help!
I think you have a minor semantic error that's causing your script to not function as expected. Also, to achieve the functional behaviour for the <select> you will need to do a few extra things, namely, to listen to the change event:
<script>
// Store variables to elements we want to work with
var mainCat = document.getElementById("main_cat")
var customFields = document.getElementById("custom_fields")
// When the website first loads, hide "custom_fields" by default
customFields.style.display = "none";
// When the user changes the main_cat select, check it's value. If
// value == "-1" then hide custom_fields. Otherwise display custom
// fields as inline
mainCat.addEventListener("change", function() {
if (mainCat.value == "-1")
{
customFields.style.display = "none";
}
else
{
customFields.style.display = "inline";
}
})
</script>
As a final note, I saw that the script was actually commented out on your website. Just below the <!--Script Custom Fields-->, the script was enclosed in /* ... */ - remove those to ensure that the script does run, rather than be ignored by the browser.
Hope this helps!

Change Twitter Widget appearance on-the-fly

I have the following code in my document:
<a class="twitter-widget" href="url" data-widget-id="138843679974442730">Twitter Timeline</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
data-widget-id is connected to one style. Right now if there is a theme change on the website (I replace all responsible stylesheets and images) everything changes but the Twitter widget.
Since the widget itself is an iframe, I can't change any stylesheets attached to it.
Is there an easy way to change the style of the widget without reloading it (deleting the tag, creating the tag, running js)?
You can style elements in the Twitter widget iframe using JavaScript.
First, you need the active document in the iframe's nested browsing context:
var doc = document.getElementById("twitter-widget-0").contentDocument;
Then, you can apply styles (e.g.):
doc.querySelector(".timeline-header").style["background-color"] = "black";
doc.querySelector(".timeline-header a").style["color"] = "white";
Example: http://codepen.io/smockle/pen/IJHnj
There is no straight forward way of doing this, so I've decided to bring in another dependency that will be delaying the onload event..
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
And here is the code that did the job:
var twitterBox = document.getElementsByClassName("twitterBox");
if (!twitterBox || twitterBox.length == 0) { return true; }
var twitterTimeline = document.createElement('a');
twitterTimeline.className = 'twitter-timeline';
twitterTimeline.href = 'url';
twitterTimeline.innerHTML = 'Twitter Timeline';
twitterTimeline.setAttribute('data-widget-id', '388742673974046720');
twitterBox[0].removeAttribute('data-twttr-id');
twitterBox[0].innerHTML = '';
twitterBox[0].appendChild(twitterTimeline);
twttr.widgets.load();

CKEditor cannot remove toolbar until I click it

I'm currently using CKEditor and I'm having some trouble removing my toolbar when I click away. Currently I want to create CKEditor instances dynamically as users click on it.
However the trouble comes up when I try to click away without clicking on the toolbar. When I try to click away on the toolbar stays there and it does not run any of my onBlur code. It's only when I click on a button the toolbar or click away and then click back to the text area will it remove the toolbar and run my onBlur code.
Right here is a small snippet of code that I wrote to create the instance when clicked. Am I doing something wrong here or am I missing a piece of focus code?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="ckeditor\ckeditor.js"></script>
<script>
$(document).ready(function(){
CKEDITOR.disableAutoInline = true;
$("#abc").on('click', function(){
var ck = CKEDITOR.inline(CKEDITOR.document.getById('abc'));
});
});
</script>
</head>
<body>
<div id="abc" contenteditable="true" >
Edit this
</div>
</body>
</html>
Try removing the jquery on click and simply allow ckeditor to handle it
$(document).ready(function () {
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline('abc');
});
OR
var abcEditor = CKEDITOR.inline('abc');
So instead of making it on click I did it so that on page load it will find all content editable areas and create ckeditor instances.
Originally I wanted to use on click to create an instance dynamically as I will be populating things dynamically. However, I found it easier to just create a ckeditor instance as I create the dynamic content.
Using this function I am able to create new ckeditor instance as the dynamic content is created and also use the onblur function to write everything to my database.
If any one has any solutions to getting the raw html from ckediter, please let me know. This method has to get the parent and then find the element and then save it, which to me doesnt sound right. So if you have any suggestions on how to do this I'm all open ears! thanks!
if(CKEDITOR.instances[this.id] == undefined){
console.log("creating new instance");
var ck = CKEDITOR.inline(CKEDITOR.document.getById( this.id ));
ck.on('blur', function(e){
var id = e.editor.name;
var html = $("#"+id).parent()[0].outerHTML;
console.log(html);
$.ajax({
type: 'POST',
url: "saveHtml",
data: { content : html}
}).done(function(data) {
console.log(data);
console.log("finished sending data");
});
});
}else{
console.log("no instance created");
}

How can I dynamically create a tweet button?

I'm currently trying to create a tweet button with the horizontal count feature dynamically:
JavaScript
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-url','http://mindcloud.co.uk/idea/?idea=' + this.id);
twitter.setAttribute('data-count', 'horizontal');
twitter.setAttribute('data-via', 'jtbrowncouk');
twitter.style.top = '20px';
twitter.style.left = '300px';
twitter.innerHTML = "Tweet";
The problem i'm having is that the button is being displayed as a text link, not as a button with the horizontal count box.
I've created a facebook button in the same way, which works correctly, however to make it work I use the following:
JavaScript
var facebook = document.createElement('fb:like');
facebook.setAttribute('id', 'like'+this.id);
facebook.setAttribute('href', 'http://mindcloud.co.uk/idea/?idea=' + this.id);
facebook.setAttribute('layout', 'button_count');
facebook.setAttribute('send', 'false');
facebook.setAttribute('width' , '300');
facebook.setAttribute('font', '');
facebook.setAttribute('show_faces', 'true');
facebook.style.top = '0px';
facebook.style.left = '300px';
using the following:
FB.XFBML.parse();
to parse and draw the button. FB.XFBML.parse() comes from
http://connect.facebook.net/en_US/all.js
When I create the Tweet button statically inside a .html file it works correctly. I'm including the following script within my index page where the tweet button should be created dynamically:
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
If you can see what i'm doing incorrectly please inform me!
The following screenshot gives a visual explanation to what is going wrong with the tweet button!
Solution:
I've now managed to solve the problem. The problem i'd imagine is that the twitter script is running on load, and not being re-run upon creating the element.
using the following jQuery works correctly!
$.getScript("http://platform.twitter.com/widgets.js");
It's worth noting that as of recently you can use the following twitter widget function:
twttr.widgets.load();
Assuming you've loaded the widgets.js file:
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
This will dynamically re-create the tweet button for you.
I've now managed to solve the problem. The problem i'd imagine is that the twitter script is running on load, and not being re-run upon creating the element.
using the following jQuery works correctly!
$.getScript("http://platform.twitter.com/widgets.js");
You're just using the wrong code. To specify the URL, you use url, not data-url. This works:
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('url','http://mindcloud.co.uk/idea/?idea=' + this.id);
twitter.setAttribute('data-count', 'horizontal');
twitter.setAttribute('data-via', 'jtbrowncouk');
twitter.style.top = '20px';
twitter.style.left = '300px';
twitter.innerHTML = "Tweet";
For more details, check out Twitter's documentation at https://dev.twitter.com/docs/tweet-button#properties

Writing a custom javascript event

I'm writing some code that will get executed before the DOM loads, basically, using Modernizr to get scripts. Now my issue is that I want to show a loading animation if the DOM loads and the scripts are still loading.
Modernizr is executed in the head. If I put the code to use document.getElementById in the head also, error is thrown because the DOM hasn't loaded. Now I have no idea how to solve this.
Here is the code I have so far:
<head>
<script>
var FileManager = {
IsLoading = false;
LoadRequiredFiles: function (config) {
config = config || {};
this.OnLoading = config.onLoadingCallback;
this.OnComplete = config.onCompleteCallback;
this.IsLoading = true;
if (this.OnLoading) {
this.OnLoading();
}
var self = this;
Modernizr.load([{
load: '/jquery.min.js',
complete: function () {
if (self.OnComplete) {
self.OnComplete();
}
self.IsLoading = true;
}
},
]);
}
};
var globalLoadingId = 'globalLoader';
FileManager.LoadRequiredFiles({
onLoadingCallback: function () {
document.getElementById(globalLoadingId).style.display = 'block';
},
onCompleteCallback: function () {
document.getElementById(globalLoadingId).style.display = 'none';
}
});
</script>
I used to execute this code below the <body> tag, and it worked. Now I moved it into the <head>. So I used to pass 2 callbacks to it. Now I'd rather attach events to it and handle them in the body (assuming thats where the DOM is loaded).
What I'd like to do:
<head>
<script>
FileManager.LoadRequiredFiles();
</script>
</head>
<body>
<script>
//Bind the event, not sure if this is even possible in javascript.
FileManager.OnCompleted += fileManagerCompleted;
fileManagerCompleted()
{
document.getElementById(globalLoadingId).style.display = 'none';
}
if(FileManager.IsLoading)
{
document.getElementById(globalLoadingId).style.display = 'block';
}
</script>
</body>
The page is your canvas for display. You can't show anything before it loads. It sounds more like you want a very small page to load (quickly) where you could display your progress and then your code could dynamically load/display the rest of the page with ajax calls and javascript showing progress as it goes. That's the only way to get out in front of the rest of the page load that I know of.
The only entirely reliable way to run a script that manipulates the DOM is to use the body onload event. (window.onload is popular, but not quite 100% reliable.)
There are some browsers that implement a onDocumentReady event that can be kind-of-sort-of faked in IE, but I don't recommend its use.
Using getElementById will not, by itself, throw an error if used in the head. You might be causing an error because you aren't checking the returned value, which will be null if an element with the specified id wasn't found, e.g.
var el = document.getElementById('foo');
if (el) {
// do somethig with el
} else {
// el wasn't found
}
Your problem is how to display the image only if the scripts are still loading and the page is visible. The simple answer is don't use client-side script loading, do it at the server. :-)
If you want to persist with script loading, add a class to the loading image, say "hideOnLoad". Have a callback from the last script load that sets the rule to "display: none" (just create and add style sheet with that one rule using script).
Now you just include the loading image as the first element in the body with a class of "hideOnLoad", knowing that when scripts have finished loading they will hide the image regardless of whether it (or any other element with the same class) existed at the time or not.

Categories