Click event to delete and refresh div content - onclick

As a noob to the JS universe, I had a question pertaining to a click event for a basic Quote Generator program. The idea is that upon clicking the '.generate' button, the content that appears within the 'taskEl' paragraph is deleted and refreshed with the next randomly generated quote. Thank you for any help with this.
<body>
<div class="card">
<button type ="button" class="generate">Generate Quote</button>
</div>
<script>
const quote = document.querySelector('.generate');
const card = document.querySelector('.card');
const myQuotes = ['It was the best of times, it was the worst of times', 'To the victor belong the spoils', 'Float like a butterfly, sting like a bee', 'No man is an island'];
const people = ['Charles Dickens', 'William Marcy', 'Muhammad Ali', 'John Donne'];
quote.addEventListener('click', getQuote);
function getQuote() {
const taskEl = document.createElement('p');
const taskEl2 = document.createElement('p');
let random = Math.floor(Math.random() * myQuotes.length);
taskEl.className = 'outputBox';
taskEl.appendChild(document.createTextNode(myQuotes[random]));
card.appendChild(taskEl);
taskEl2.className = 'sourceBox';
taskEl2.appendChild(document.createTextNode(people[random]));
card.appendChild(taskEl2);
};
getQuote();
</script>

I'd suggest you to place click attribute inside html element, like this:
<button type ="button" class="generate" onclick="getQuote()">Generate Quote</button>
To substitude the contents of a paragraph use innerText.
taskEl.innerText = 'some random quote';

Related

Dynamic Refs in Vue3

Can someone please help me understand dynamic refs in Vue3? I have a group of radio buttons and trying to return the value of the selected button. In the code below the same value is returned regardless of which button I click.
<script setup>
const props = defineProps({
mealServices: Array,
});
const activeMealService = ref([])
const setActiveMealService = () => {
console.log('meal id is ' + activeMealService)
};
</script>
<div v-for="mealService in mealServices" :key="mealService.id">
<input :ref="(el) => {activeMealService = mealService.meal_type_id}"
#click="setActiveMealService" type="radio" name="meal_type"
:id="mealService.meal_type_id"
:value="mealService.meal_type_id"
v-model="form.meal_type_id"/>
<label :for="mealService.meal_type_id">{{ mealService.meal_type.name }}</
</div>
:ref="(el) => {activeMealService = mealService.meal_type_id}" is called for every iteration, right?
I guess you're resetting the active meal in every render to the last meal.
You don't need a Template ref to get the current selected meal.
Try removing this line

Display json local

I have been trying to display JSON data from one page to another on click.
For example, a user clicks on an image and it passes the same image/text to another page.
Here is my code
ygt.js
<h2 class="pet-name">${pet.name}
<h1 class="species">${pet.species}
</div>
<div></div></div>
</div>
</div>
`;
}
document.getElementById("app").innerHTML = `
<h1 class="app-title">Kids
${petsData.map(petTemplate).join("")}
`;
You can use localStorage to pass the values from one page to another. Let's say you have the books in one page and you want to pass the book name to another page.
In your books page, you can add a function like this:
function saveBook(bookName, link){
localStorage.setItem("bookName", bookName):
window.location.href = link
}
Then you can call this function in your onclick event.
<div class="olay" onclick="saveBook('The Book','${pet.href}');" style="cursor: pointer;">
When someone clicks on the book, it will save the value in the localStorage and redirect to the page you need.
In the second page, you can use a function to retrieve the saved value:
var bookName = localStorage.getItem('bookName');
More info on localStorage : https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Pull URL parameters into a WordPress "Raw HTML" content element

I'm using the URL Params plugin to pull parameters into regular content using a short code. But I have to use a Raw HTML block to insert Typeform code into the page and I want to be able to pass a URL parameter into the Typeform code to track the source of the form submission.
I can't figure out how to do it. The form is working fine at: https://HelloExit.com/instant-valuation
But I want to be able to send people to https://HelloExit.com/instant-valuation/?source=XXXX and pull the XXXX into the Typeform code as the "source" value in the "data-url"
Here's what I tried:
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var source = getUrlVars()["source"];
</script>
<div
class="typeform-widget"
data-url="https://xgenius.typeform.com/to/zZHPPk?source=<script>document.write(source)</script>"
data-transparency="100"
data-hide-headers=true
data-hide-footer=true
style="width: 100%; height: 500px;">
</div>
<!-- Typeform embed code -->
<script>(function() { var qs,js,q,s,d=document, gi=d.getElementById,
ce=d.createElement, gt=d.getElementsByTagName, id="typef_orm",
b="https://embed.typeform.com/"; if(!gi.call(d,id)) { js=ce.call(d,"script"); js.id=id;
js.src=b+"embed.js"; q=gt.call(d,"script")[0]; q.parentNode.insertBefore(js,q) } })()
</script><div style="font-family: Sans-Serif;font-size: 12px;color: #999;opacity: 0.5;padding-top: 5px;"> powered by Typeform</div>
Any assistance would be greatly appreciated!
You're close, but you'll need to use Javascript to alter the data-url attribute of your div.
// ...
var source = getUrlVars()["source"];
// concatenate the url with your source variable
var newUrl = `https://xgenius.typeform.com/to/zZHPPk?source=${source}`;
// get the element whose attributes you want to dynamically set
// https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var widgetElement = document.querySelector('.typeform-widget');
// set the source attribute
// https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
widgetElement.setAttribute('data-url', newUrl);
Test this carefully, as it might still end up with a race condition (that is, the Typeform embed code might start running before you've updated the data-url attribute that it references).

wordpress ajax pagination with history

(premise: this is a pretty noob question)
Hi guys,
I am try to code a good ajax navigation/pagination for WordPress.
Currently I am trying to append the new page articles instead of replacing the old ones.
In archive.php I've replaced <?php the_posts_navigation(); ?> with
<nav class="navigation posts-navigation" role="navigation">
<div class="nav-links">
<div class="nav-previous">
<?php next_posts_link(); ?>
</div>
</div>
</nav>
since I want to display only the "Next page" link (which I will style in a button later).
And in my js file I have
$('.nav-previous a').live('click', function(e){
e.preventDefault();
$('.navigation').remove(); // Removing the navigation link at the bottom of the first articles
var link = $(this).attr('href');
$.get( link, function(data) {
var articles = $(data).find('.archive-container');
$('#primary').append(articles);
});
});
It is not that clear to me how to implement history handling in a context like this. I'd like to give users the possibility to scroll up to previous results when clicking on the back button and to keep the results when someone clicks on an article and then goes back to the results.
Now, if I use something like window.history.pushState('', '', link); at the end of the click function above, it changes the URL when pushing the link to see the next articles. And this is correct. But, if I click on an article (e.g. of /page/2) to see it and then I click on the back button, it shows only the results of the page containing that article (that is /page/2 in my example). I'd like to show again all the articles the user saw before leaving the archive page instead.
At the moment I'm also working with window.localStorage to reach the goal, but I'd like to understand if it could be feasible only with history and how to do it.
console.log(window.location.href);
let loc = window.location.href.slice(0, -1);
let ppos = loc.indexOf("page/");
if((ppos >= 0)) {
let page = parseInt(loc.slice(loc.lastIndexOf('/') + 1, loc.length)) + 1;
loc = loc.slice(0, ppos) + 'page/' + page + '/';
} else {
loc += '/page/2/';
}
console.log(loc);
window.history.pushState('', '', loc);

Draggable UI Values with Meteor Handling Reactivity (see Bret Victor's Tangle)

Bret Victor created a cool library called Tangle for reactive documents a few years ago. You can see an example here:
http://worrydream.com/Tangle/TangleTemplate.html
I love the simple way you can drag values. I am trying to build a simple mortgage calculator where you could drag interest rate, years, etc. My hope was to do something similar in my UI and have Meteor handle the reactivity.
My initial thought is to leverage the UI elements of TangleKit (http://worrydream.com/Tangle/TangleKit/) perhaps via creating a package out of the JS files? I don't know the best way or if there are other ways. So looking for advice or ideas to get to the end result with Meteor.
The full doc is here:
http://worrydream.com/Tangle/download.html
The Git repo is here:
https://github.com/worrydream/Tangle
Thanks for any guidance. This is all new to me.
------- UPDATED 4/14 9PM PST
Still no luck, but close I think. See below.
COFFEE:
if Meteor.isClient
console.log "Client is alive."
Session.set("cookies", 4)
Template.reactive.cookies = () ->
Session.get("cookies")
Template.reactive.calories = () ->
Session.get("cookies") * 50
Template.reactive.events
'click .EditableValue': () ->
newCookies = Math.round(accounting.formatNumber((Random.fraction() * 10),1))
Session.set("cookies", newCookies)
Template.example.rendered = () ->
element = #find("#example") # Searches only within this template
tangle = new Tangle(element,
initialize: ->
#cookies = 4
#caloriesPerCookie = 50
update: ->
#calories = #cookies * #caloriesPerCookie
# Insert your Meteor updating code here, for example:
Session.set("cookiesQuantity", #cookies)
)
Template.example.cookies2 = () ->
Session.get("cookiesQuantity")
if Meteor.isServer
console.log "Server is alive."
HTML:
<head>
<title>Reactive Document</title>
</head>
<body>
{{> reactive}}
{{> example}}
</body>
<template name="reactive">
<h5>This is a simple reactive document.</h5>
<h4 id="example">When you eat <span class="EditableValue"> {{cookies}} cookies</span>, you will consume <span class="ReactiveValue"> {{calories}} calories</span>.</h4>
</template>
<template name="example">
<p>This is a simple reactive document.</p>
<p id="example">When you eat <span data-var="cookies"
class="TKAdjustableNumber" data-min="2" data-max="100"> cookies</span>, you
will consume <span data-var="calories"></span> calories.</p>
{{cookies2}}
</template>
It looks like you can just use Tangle as-is, and within the tangle’s update function, add a line or two to tell Meteor about the change.
Taking the example you linked to, convert the page into a Meteor template:
<template name="example">
<p>This is a simple reactive document.</p>
<p id="example">When you eat <span data-var="cookies"
class="TKAdjustableNumber" data-min="2" data-max="100"> cookies</span>, you
will consume <span data-var="calories"></span> calories.</p>
</template>
Then you initialize the Tangle inside that template’s rendered callback:
Template.example.rendered = function () {
var element = this.find("#example"); // Searches only within this template
var tangle = new Tangle(element, {
initialize: function () {
this.cookies = 4; // Or Session.get("cookiesQuantity"), for example
this.caloriesPerCookie = 50;
},
update: function () {
this.calories = this.cookies * this.caloriesPerCookie;
// Insert your Meteor updating code here, for example:
Session.set("cookiesQuantity", this.cookies);
}
});
And make sure you put Tangle's files inside a client/lib/tangle folder so that they get sent to the client.

Resources