bind svelte elements from {#html} directive - javascript

I'm trying to take user input and find all the texts that look something like this
>>523 like imageboards do. I convert these to HTML template strings through the regex replace method and sanitize the string. then I put the string in to svelte with {#html input}. It works very well but I have a few issues.
Here is the link to a REPL
https://svelte.dev/repl/737a125144474234a100cd871c1d4d5b?version=3.42.6
If you look in the console (for some reason it makes me use devtools console, repl console does not work) you can see it gets me the two a elements there, but the forEach method does not work
I want the created element to link to the referenced post. but one post can have many quote link elements in it. and I have no idea how to get a variable reference to them because I can't use {#each} and I tried this inside onMount:
let quotes = document.getElementsByClassName('postlink');
quotes.forEach((q) => {
q.addEventListener('mouseover', (e) => {
console.log('mousing over q:', q);
});
q.addEventListener('mouseout', (e) => {
console.log('mouse left q:', q);
});
});
console.log(quotes);
And it gives me a type error in the console.
Uncaught TypeError: quotes.forEach is not a function
How can I accomplish this? I want the mouseover and mouseout events to show a preview of the post the quotelink links to.

document.getElementsByClassname returns a NodeList object which doesn't have the forEach function defined, you can parse it to an array like this [...quotes].forEach

Related

Add parameters to url with onSubmit using a Javascript function

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.
I was thinking about doing something like this:
function onSubmitForm() {
url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
//I don't know how to actually call the url.
}
EDIT
I got what I wanted:
Appending form input value to action url as path
First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.
function onSubmitForm() {
window.location = "localhost:8080/test/index.php?Title=" +
document.querySelector('title').textContent;
}
NOTES:
Only form fields have a .value property. If you are trying to get
the text within an element, you can use .textContent.
.getElementsByName() scans the entire document and makes a
collection of all the matching elements. That's wasteful when you
know you want only the first one and, in the case of <title>, there
is only ever going to be one of those in a document anyway. Use
.querySelector() to locate just the first matching element.
ES6
NOTES :
Don't forget to use Babel for converting your code in ES5.
I purpose to you this solution :
function onSubmitForm() {
window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}`
}
This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.
Here we have more of that. And we can write on several lines as well.
Then ${} is used to pass a variable inside
Documentation if you want : Literal template string

Getting element from DOM with jQuery

EDIT:
JSFIDDLE here. I am trying to mirror DESKTOP 1 to MOBILE 1 elements (same for #2) in the fiddle. The error is shown in console.
Got to DESKTOP 1 and select NEW RATE from the list. Have the console opened to see the issue. Thanks!
I get an element from my layout with this command:
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get();
I then try to toggle it:
toggleField($(eqTaxSelect), $(eqTaxSelect).nextElementSibling); <-- FAILS
function toggleField(hideObj, showObj) {
hideObj.style.display = 'none'; <-- FAILS HERE
showObj.style.display = 'inline';
showObj.focus();
}
with:
Uncaught TypeError: Cannot set property 'nextElementSibling' of undefined
What am I doing wrong when assigning the element to my variable? This function works for this inside click event listeners for example.
Thanks!
The HTML I am toggling came from this forum, essentially a select with a hidden input so new entries can be added as well as using an entry from the options list.
What am I doing wrong when assigning the element to my variable?
You are passing jQuery() objects, where toggleField expects DOM elements. jQuery() does not have a .nextElementSibling method. Remove calls to jQuery() at
toggleField($(eqTaxSelect), $(eqTaxSelect).nextElementSibling);
replace with
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling);
to pass DOM elements to toggleField.
test with
console.log(eqTaxSelect)
see on inspector (CTRL+SHIF+I CHROME). if this is ok,
just do this
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling)
withouth "$"
The reason why your statement
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling);
fails is because of the way you are populating the eqTaxSelect
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get();
It should be modified as
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get(0);
reason being, get() without an index returns an array and the way you are operating, you are expecting an single dom element.
jQuery documentation for get()

run jQuery function by inline onClick and use function variable/reference

I am very new to this, but I wrote this and thought it would work first time, but I get an 'ReferenceError: Can't find variable: street' console error.
I get this error if I click on the 'Street' button.
It's quite basic but this is the first time I've made a function to use a var/ref from the onClick attribute.
Please see onClick markup...
Supersport
Street
Cruiser
Scooter
Motocross
Enduro
Kids
then please see my function, which gets the ref error above...
Also please note I am trying to use the onClick var/ref within my function so I can target specific elements relative to the button being clicked.
bikeFilter = function (y) {
$('.bike').fadeOut();
scrollTo(186);
$('.bike[data-group=' + y + ']').fadeIn();
bikeSliderNav();
bikeSlider();
return false;
}
Any expert advice would be really helpful.
Thanks in advance.
You'd probably wanna pass a String as input to your function and not the name of an undeclared and uninstantiated variable.
Try to use the single quotes to refer it as a String constant (you need single quotes since you are already using double quotes to tell your html tag the attribute value):
onclick="bikeFilter('scooter')"
Take a look here to see the difference in data typing in js, and here for a quick start about functions.
You should use them like :
onclick="bikeFilter('motocross')"
Don't forget to put ' around your parameters

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:
$("selector").live('click')
but now when I wanna use it in another function.
but It will not work with out argument,like it live()
for e.g followin code will alert test (work)
var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
but this will not.
var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
how can I solve it?
You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:
function pos_eq() {
var list = $('.myList');
var left = parseInt(list.css("left"));
var width = parseInt(list.children('li').eq(0).css('width'));
return Math.abs(left / width) + 1;
}
I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:
alert(pos_eq);
alert(pos_eq());
To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.
There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.
The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

Is there a way to make jQuery output *actual markup*?

When using jQuery to dynamically build markup, it sometimes becomes useful to have it return the actual HTML that it's generating as a string, rather than as a bunch of jQuery objects. Is there a way to do this? For example, here:
$("<strong></strong>").text("Hi there!");
I want to be able to extract the plain-text string
"<strong>Hi there!</strong>"
so that I can cache it remotely. Is there a way to do this?
Yes, you can use the html() function
i.e.
$("").text("Hi There!").html();
Will return 'Hi There!'
Keep in mind this uses innerHTML, so
$("<div><b>Foo</b></div>").html();
will return
<b>Foo</b>
As a result you'll need to wrap your code in a surrounding div or span.
You can use a outerHTML plugin for that. Here is one:
jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}
Usage:
alert($("<strong></strong>").text("foo").outerHTML());
// alerts <strong>foo</strong>
Just call .html() to get HTML from any element, including generated ones. This is from a Chrome developer tool session:
> $("<div><span>blerg</span></div>")
Object
> $("<div><span>blerg</span></div>").html()
<span>blerg</span>
You can see, the first one returned an object, the second returns text.

Categories

Resources