HTML5 → Dynamic associated Server Sent Events - javascript

I just started using SSE and wonder how I can make them more dynamic.
I'm using a Box to select users and an image and text changes corresponding to the username.
Now I want to check for user updates via SSE and want the user to be still selectable.
I tried to add the eventSource when I'm changing the <select> box:
function setSelected(elm) {
selectedName = elm.options[elm.selectedIndex].innerHTML;
var eSource = new EventSource("getState.php?passVar=" + selectedName);
eSource.onmessage = function(event) {
document.getElementById("stateText").innerHTML = event.data;
};
}
How can I reach my goal?
edit
I have now added the eventSource successfully (I had an issue with the source itself).
But when I now add another source, I have actually two sources running.
How can I remove the old one?

To remove the previous event source use the close() method. You're going to have to keep the reference to eSource around somehow to do this.

Related

How can I create a dynamic product page using HTML, CSS, and Javascript

I currently only know javascript. But the thing is I looked up how to do it and some people talk about something called localStorage. I have tried this and for some reason when I jump to a new page those variables aren't kept. Maybe I am doing something wrong? I jump to a new page via
and all I want do do is select a certain image. take that image to a new page and add it to that page.
I tried using the localStorage variables and even turning it into JSON.stringify and doing JSON.parse when trying to call the localstorage to another script. It didn't seem to work for me. Is there another solution?
This is some of my code. There are two scripts.
document.querySelectorAll(".card").forEach(item => {
item.addEventListener("click", onProductClick);
})
var div;
var productImg;
var ratingElement;
var reviewCount;
var price;
function onProductClick(){
// This took a week to find out (this.id)
// console.log(this.id);
div = document.getElementById(this.id);
productImg = div.getElementsByTagName('img')[0];
ratingElement = div.getElementsByTagName('a')[2];
reviewCount = div.getElementsByTagName('a')[3]
price = div.getElementsByTagName('a')[4];
console.log(div.getElementsByTagName('a')[4]);
var productData = [div, productImg,ratingElement,reviewCount,price];
window.localStorage.setItem("price", JSON.stringify(price));
}
function TranslateProduct(){
console.log("Hello");
}
This is script 2
var productPageImage = document.getElementById("product-image");
var myData = localStorage['productdata-local'];
var value =JSON.parse(window.localStorage.getItem('price'));
console.log(value);
// function setProductPage(img){
// if(productImg != null){
// return;
// }
// console.log(window.price);
// }
To explain my thought process on this code in the first script I have multiple images that have event listeners for a click. I wanted to Click any given image and grab all the data about it and the product. Then I wanted to move that to another script (script 2) and add it to a dynamic second page. yet I print my variables and they work on the first script and somehow don't on the second. This is my code. in the meantime I will look into cookies Thank you!
Have you tried Cookies
You can always use cookies, but you may run into their limitations. These days, cookies are not the best choice, even though they have the ability to preserve data even longer than the current window session.
or you can make a GET request to the other page by attaching your serialized object to the URL as follows:
http://www.app.com/second.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using JavaScript.
you can check this answer for more details Pass javascript object from one page to other

How to store a newly created element to localStorage or Cookie with Javascript?

I am making an idle clicker game for fun, everything was going fine until I encountered a problem.
What I basically want to happen is when the image is clicked and the clickCounter element is over one, the new image element is created. No problem here, the main problem is saving the image. If the user refreshes the page, I want the created element to still be there. I have tried using outerHTML and following some other Stack Overflow forum questions but I could never get a proper solution to this certain problem. I have also tried localStorage and cookies but I believe I am using them wrong.
My code is below, my sololearn will be linked below, consisting of the full code to my project.
function oneHundThou() {
var countvar = document.getElementById("clickCounter")
if(document.getElementById("clickCounter").innerHTML > 1) {
alert("Achievement! 1 pat!")
var achievement1k = document.createElement("img");
// create a cookie so when the user refreshes the page, the achievement is shown again
document.cookie = "achievement1k=true";
achievement1k.src = "https://c.pxhere.com/images/f2/ec/a3fcfba7993c96fe881024fe21e7-1460589.jpg!d";
achievement1k.style.height = "1000px"
achievement1k.style.width = "1000px"
achievement1k.style.backgroundColor = "red"
document.body.appendChild(achievement1k);
oneHundThou = function(){}; // emptying my function after it is run once instead of using a standard switch statement
}
else {
return
}
}
oneHundThou();
I am aware that there is another post that is similar to this, however, my answer could not be answered on that post.
Full code is here: https://code.sololearn.com/Wwdw59oenFqB
Please help! Thank you. (:
Instead of storing the image, try storing the innerHTML, then create the image on document load:
function oneHundThou() {
countvar.innerHTML = localStorage.getItem('clickCount') ? localStorage.getItem('clickCount') : 0; //before if
//original code
localStorage.setItem('clickCount', countvar.innerHTML); //instead of doc.cookie
}
window.addEventListener('DOMContentLoaded', (event) => {
oneHundThou();
});
or, if you don't care that clickCounter may initialize to null, you can remove the ? : and just put
countvar.innerHTML = localStorage.getItem('clickCount');
Edit: shortened code with the countvar variable

Insert a text into a textbox and simulate click on the button in Bot Framework's Web Chat

Fiddle here: https://jsfiddle.net/chpaeeL9/1/
Microsoft Bot Framework has a webchat module that allows you to talk to your bot.
When the user clicks the Say Hi button, I want to place some text into the webchat's textbox, and click the Send button inside the webchat using JavaScript.
Sounds like something too easy, but it wasn't. Here's the code that I currently have, and it doesn't work: the click event somehow is not triggered.
$('#sayhibutton').click(function() {
$('.wc-console').addClass('has-text'); // works
$('.wc-shellinput').val("Hi bot!").change(); // works
$('.wc-send').click(); // doesn't work!
$('.wc-send svg').click(); // doesn't work either
});
Update: if that helps, it seems the interface is written using React.
Update: my question is different from my previous question about how to avoid iframes in webchat.
OK, for the lack of a better option my solution was a pretty dirty and ugly one.
Save the code in botchat.js into a file and reference that saved file from the HTML, rather than the CDN version.
Pretty-print the file in Chrome and find the line that says:
e.prototype.sendMessage = function() {
this.props.inputText.trim().length > 0 && this.props.sendMessage(this.props.inputText)
}
Replace the middle line with this:
this.textInput.value.trim().length > 0 && this.props.sendMessage(this.textInput.value)
This basically means to take the message text from this.textInput.value rather than from this.props.inputText, or in other words, take it directly from the textinput's DOM node.
Somehow triggering the change event on a textbox doesn't cause an actual change event on the textbox, which is why we need to do this.
this is an issue with react try this,
var input = document.getElementsByClassName("wc-shellinput")[0];
var lastValue = input.value;
input.value = 'YOUR MESSAGE';
var event = new CustomEvent('input', { bubbles: true });
// hack React15
event.simulated = true;
// hack React16
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
//send the message
$(".wc-send:first").click();
to read more see this post: https://github.com/Microsoft/BotFramework-WebChat/issues/680

Starting from random pages in Google Web Designer

I've been using Google Web Designer for a few months and I have a question. I don't know if it's possible to do in GWD:
I want the index.html file to load a different random page, choosing between 3 pages. When you hit reload, it should load another random page, and so on. The pages don't need to appear in order. I'm trying to find out how this can be done but I had no success so far.
This can be accomplished with a custom JavaScript event handler.
The <gwd-doubleclick> element fires an adinitialized event before any content is displayed, which we can use to make sure our changes are applied before the user sees the first page. It also provides a .goToPage(n) method which we can use to switch pages. (goToPage has additional arguments that can be used to control animation between pages, but we can ignore those because we want the default behaviour of instantly jumping.)
Start by adding a new event handler.
target: document.body
event: Google Ad: Ad Initialized
action: Custom: Add Custom Action
configuration: a name of your choice (such as gwd.goToRandomPage), for the following code:
var pages = 3; // adjust as appropriate
var targetPage = Math.floor(Math.random() * pages);
event.target.goToPage(targetPage);
In code view you can see that this produces something like the following:
// This script block is auto-generated. Please do not edit!
gwd.actions.events.registerEventHandlers = function(event) {
gwd.actions.events.addHandler('document.body', 'adinitialized', gwd.goToRandomPage, false);
};
gwd.actions.events.deregisterEventHandlers = function(event) {
gwd.actions.events.removeHandler('document.body', 'adinitialized', gwd.goToRandomPage, false);
};
You could choose to skip the GWD UI and use the standard JavaScript event handling APIs to accomplish the same thing, with something along the lines of:
document.body.addEventListener('adinitialized', function() {
var pages = 3; // adjust as appropriate
var targetPage = Math.floor(Math.random() * pages);
event.target.goToPage(targetPage);
});
However, you probably want to avoid this in general, because it will prevent GWD from handling things like element renaming automatically.
If you'd like to jump to one of a specific set of pages, instead of selecting from all pages, you could use an array of page IDs instead.
var pageIds = ['page1_1', 'page1_2'];
var targetPage = pageIds[Math.floor(Math.random() * pageIds.length)];
event.target.goToPage(targetPage);
For future reference, you can find most of the component APIs described in the documentation. Questions about GWD that do not involve code or are otherwise unsuitable for Stack Overflow should be asked on the GWD support forum instead.

Tracking user interaction on a website

I am trying to track user interaction on a website that I manage myself. By tracking I mean, I want to track which button or widget the user pressed and when and also how much time a user spent and etc. Before I dive into coding something up on Javascript, I just to get an idea what are best options to do such things and possible pitfalls.
It's been some time since this question was posted, but I've been working on a simple JavaScript module to do just this.
Rather than using images, it captures event data from user-specified HTML element(s) along side some basic information about the site visitor's browser configuration. The data is then sent to a specified server endpoint using an XHR triggered on the beforeunload event.
Here's a link to the GitHub project and an example page
Regarding the code, here's an example of what the HTML would look like:
<!DOCTYPE html>
<html>
<head>
<title>Interaction Tracker Example</title>
</head>
<body>
<div class="someElement"></div>
<div class="someOtherElement"></div>
<div class="conversion"></div>
<script src="interactor.min.js" type="application/javascript"></script>
<script>
// An example instantiation with custom arguments
var interactions = new Interactor({
interactions : true,
interactionElement : "someElement someOtherElement",
interactionEvents : ["mousedown"],
conversions : true,
conversionElement : "conversion",
conversionEvents : ["mouseup"],
endpoint : '/usage/interactions',
async : true
});
</script>
</body>
</html>
The architecture allows you to easily track multiple elements through multiple instantiations, allowing you to customize which endpoints different interactions are sent to. This allows for clean separation of any server-side pre-processing prior to saving the data to a database.
var elementsToTrack = [
{
element : "cssClass1",
events : ["mouseup", "touchend"],
endpoint : "/interactions/c1"
},
{
element : "cssClass2",
events : ["mouseup"],
endpoint : "/interactions/c2"
},
{
element : "cssClass3",
events : ["mouseup"],
endpoint : "/interactions/c3"
}
];
for (var i = 0; i < elementsToTrack.length; i++) {
var el = elementsToTrack[i];
new Interactor({
interactionElement : el.element,
interactionEvents : el.events,
endpoint : el.endpoint
});
}
Finally, it's very lightweight (about 5KB minified) and easily extendable to most needs.
If you don't need to return any value from server, ajax is a bit overhead - I would use image pings (creating image elements with script as source with any parameter you want to send)
For events, bind them to document and check event target (be aware - blur, focus and change do not bubble)
document.body.addListener(event, function() {
var i = new Image();
i.src = 'script.php?target=' + event.target;
}, false);
For time measurement, you could check time that passes between events on elements.
I would recommend looking into something like mixpanel. It's very simple to integrate and they provide you with the graphic tools to parse large amounts of data. The basic premise is similar to what you said. Fire asynchronous events on specific user interaction, passing along a set of options. You can also integrate it into your Python code, which makes it easy to track when server side actions take place. Example:
$("#my_button").click(function() {
// This sends us an event every time a user clicks the button
mixpanel.track("Button clicked");
});
You can explore the docs for yourself. https://mixpanel.com/docs/integration-libraries/javascript
Mixpanel is just one option, but the premise is the same for all. The thing you need to consider is managing that data after it's been collected. Companies like mixpanel provide a nice GUI to make it less of a headache.
Google Analytics provides a good Javascript library for this:
https://github.com/googleanalytics/autotrack
Of course, it expects you to use Google Analytics in your app, but it has a free version you can use. Check the comparison between their free and paid services.

Categories

Resources