Get data attr value on hover - javascript

I have a few links. When I hover mouse over the links I would like to get the values stored in data attributes. I need to pick the t values and pass them into function
HTML
<a href="#" data-lat="23.333452" data-lon="-97.2234234">
JS
var loc = document.querySelectorAll("a[data-lat]");
loc.addEventListener("mouseover", locOver);
loc.addEventListener("mouseout", locOut);
function locOver() {
// do something
}
function locOut() {
// do something else
}
It's been a while since I used vanilla JS and it's been a long day so I'm sure it's pretty close but I'm stuck. I keep getting:
Uncaught TypeError: loc.addEventListener is not a function
What am I missing here?

You need to loop through the nodes that you obtained with document.querySelectorAll("a[data-lat]") for adding events.
Working example.
Node
<script>
var loc = document.querySelectorAll("a[data-lat]");
loc.forEach(node => {
node.addEventListener("mouseover", locOver);
node.addEventListener("mouseout", locOut);
})
function locOver(event) {
// do something
console.log('mouseover', event.target.dataset)
}
function locOut() {
// do something
console.log('locOut')
}
</script>

const loc = document.querySelector("a[data-lat]");
const locOver = () => {
console.log("Mouse is over the link");
}
const locOut = () => {
console.log("Mouse is out of the link");
}
loc.addEventListener("mouseover", locOver);
loc.addEventListener("mouseout", locOut);
Link
Explanation:
I target the link using .querySelector method that returns a single node.
After that i created two event handler for mouseOver and mouseOut and than i added the eventListener to the link.

Related

how to pass element in inline onclick event in a dynamically created string

I got a function that creates a button template for Kendo Grid Toolbar based on the parameter received. What I want to do is passing one of the properties inside the parameter called element(it is a jquery element) through onclick function so that I can access that element in the function fnAdd(element).
function(parameter)
{
var template="<button onclick='fnAdd("+param.element+")'>Add</button>";
$('#grid').kendoGrid({
toolbar: template
});
}
Currently, the onclick function is not working. I try to use JSON.stringify on the param and pass it through the onclick and able to get it on fnAdd(), but I can't access the param.element at all.
Anyone know how to solve this?
You can use the bind method to attach your params to achieve this. Sample code below
function add(param) {
let btn = document.createElement('button');
btn.innerHTML = 'NEW - ' + new Date().getTime();
btn.onclick = newButtonOnclick.bind(this, (param || new Date().getTime()))
document.body.append(btn)
}
function newButtonOnclick(param) {
alert(param);
}
button {
display: block;
margin-bottom: 1em;
}
<button type="button" onclick="add();">
Add New Button
</button>
I hope this solution can help you:
Remember the Patter designs, in this case we can use a Factory patter with this you can reuse this code to create chunks of code.
With this example also each button could trigger a different function and can have different params!
// YOUR JAVASCRIPT WITH ACCESS TO THE DOM
// here you call your plugin where the DOM is not present
function getButton() {
let newButtonInString = createButtonPlugin();
// in newButton you just have the string
// now convert it to html using Jquery
let htmlButton = $(newButtonInString);
document.body.append(htmlButton[0]);
}
// YOUR PLUGIN JS
let counter = 1;
function createButtonPlugin() {
// you can take this params from the UI
let paramsExample = {
text: `New Button ${counter}`,
functionParams: {
counter: counter
} // Could be an object or what you want!
}
let bp = new ButtonPrototype(paramsExample);
let newButton = bp.createButton();
counter++;
// return string to the place where you can render the button
return newButton;
}
class ButtonPrototype {
constructor(params){
this.params = params
}
createButton() {
return `<button onclick=fn(${JSON.stringify(this.params.functionParams)})>${this.params.text}</button>`
}
}
function fn (args) {
alert(`Success ${args.counter}`)
}
Your html:
<button onclick="getButton()">add</button>
I also leave the codepen: Just Updated with the new comment you made!
https://codepen.io/ruben-saucedo/pen/GbxXNG

jQuery plugin method to get object properties

I´m building a jQuery extension plugin with the following standard:
(function ($) {
var version = "1.1.0";
var active = false;
$.fn.inputPicker = function (options) {
return this.each(function () {
if ($(this)[0].tagName !== 'DIV')
throw new ReferenceError('mz.ui.dialog.dateTimePicker: Method works only on DIV types.');
/// Label
var labelObj = $("<label class='small'>Data Hora Inicial</label>");
$(this).append(labelObj);
/// Input
var inputObj = $("<input type='datetime-local' class='form-control input-sm'></input>");
$(this).append(inputObj);
})
});
};
}(jQuery));
And here is how I call it:
<div id='test'></div>
$('#test').inputPicker();
Later in code I wanna get the data that was entered in the input field, something like:
$('test').inputPicker().getInputData();
What´s the best way to accomplish that ? I´ve tried something like:
this.getInputData = function () {
return $(inputObj).val();
}
But got errors when calling the function.
Can someone help me with this ? Thanks in advance...
You could just make another method to get the input data like this using the DOM structure and class names that you added:
$.fn.getInputData = function() {
return this.eq(0).find("input.input-sm").val();
}
This would operate only on the first DOM element in the jQuery object (since it's returning only a single value).
So, after setting it up like you did:
$("#test").inputPicker();
You'd then retrieve the data like this:
var data = $("#test").getInputData();

Jquery - binding click event to a variable

All,
I am really stuck/ confused at this point.
I have an array with 6 items in it. Each item in the array is dynamically filled with elements using jquery '.html' method. However, I cannot seem to be able to attach/ bind an event to this dynamically created variable.
As soon as the browser gets to the problem line (see the area labeled 'PROBLEM AREA'), I get a 'undefined' error, which is really confusing as all the previous code on the very same variable works just fine.
var eCreditSystem = document.getElementById("creditSystem");
var i = 0;
var eCreditT = new Array(6); // 6 members created which will be recycled
function createCreditTransaction () // func called when a transaction occurs, at the mo, attached to onclick()
{
if (i < 6)
{
eCreditT[i] = undefined; // to delete the existing data in the index of array
addElements (i);
} else
if (i > 5 || eCreditT[i] != undefined)
{
...
}
}
function addElements (arrayIndex) // func called from within the 'createCreditTransaction()' func
{
eCreditT[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
$(eCreditT[i]).attr ('id', ('trans' + i));
$(eCreditT[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span> <img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
creditTransactionSlideOut (eCreditT[i], 666); // calling slideOut animation
console.log(eCreditT[i]); // this confirms that the variable is not undefined
/* ***** THE PROBLEM AREA ***** */
$(eCreditT[i]).on ('click', function () // if user clicks on the transaction box
{
creditTransactionSlideBackIn (eCreditT[i], 150); // slide back in animation
});
return i++;
}
Try this:
$(eCreditT[i]).bind('click', function() {
creditTransactionSlideBackIn(eCreditT[i], 150);
});
Edit: use ++i instead of i++ like this:
return ++i;
/*
or
i += 1;
return i;
*/
retrurn ++i performs the increment first then return i after the increment.
While return i++ return i then icrement it.
Try to add click event out of addElements() function and try once.
Nonsense create an element using JavaScript and then use jQuery function to transform it into a jQuery object. You can let jQuery create the element directly for you.
eCreditT[i] = $('<div>').addClass("cCreditTransaction").appendTo(eCreditSystem);
Also, since eCretitT[i] is already a jQuery element, no need to call the jQuery function again.
eCreditT[i].on('click', function () {
creditTransactionSlideBackIn(eCreditT[i], 150);
});
If you already tried on, bind, live and click methods, then maybe the called function is your problem. Try to put a console.log() or an alert() inside the function to make sure the click event is actually happening. If it happens then the function creditTransactionSlideBackIn() is your problem.
EDIT
The problem is when the event takes place, i is not the original variable anymore.
function addElements (arrayIndex)
{
eCreditT[i] = $('<div>').addClass("cCreditTransaction").appendTo(eCreditSystem);
eCreditT[i].attr ('id', ('trans' + i));
eCreditT[i].data ('id', i); // Store the id value to a data attribute
Then when you call the function you can refer to the data attribute instead of the i variable:
/* ***** THE PROBLEM AREA ***** */
eCreditT[i].on ('click', function () // if user clicks on the transaction box
{
creditTransactionSlideBackIn ($(this).data('id'), 150); // slide back in animation
});
return i++;
}
try to bind parent div and then use if($e.target).is('some')){}, it will act as .live, like this:
$(eCreditSystem).bind('click', function (e){
if($(e.target).is('.cCreditTransaction')) {
creditTransactionSlideBackIn ($(e.target), 150);
}
});
of course you'll need in a minute larger if for checking if clicked dom el is a child of .cCreditTransaction, like this:
if($(e.target).parents().is('.cCreditTransaction')){}
Try this:
$(eCreditT[i]).live('click', function() {
creditTransactionSlideBackIn(eCreditT[i], 150);
});

Is it possible to bind to the Click event and not use an anonymous function -- I just want to call a named function

I have the following code. The first attempt at binding to click event does not work. The second way does. The first shows the alert "CheckBox1" during Page_Load. The second one shows the alert "CheckBox4" during the proper time -- during clicks.
$(document).ready(function () {
$(document.getElementById(checkBox1ID)).click( SetCheckBox1State(this.checked) );
$(document.getElementById(checkBox4ID)).click(function () { SetCheckBox4State(this.checked) });
});
function SetCheckBox1State(checked) {
alert("CheckBox2");
var radNumericTextBox1 = $find(radNumericTextBox1ID);
var wrapperElement = $get(radNumericTextBox1._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox1.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox1.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
function SetCheckBox4State(checked) {
alert("CheckBox4");
var radNumericTextBox2 = $find(radNumericTextBox2ID);
var wrapperElement = $get(radNumericTextBox2._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox2.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox2.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
Am I doing something improper? I'd rather not use an anonymous function...but maybe this just how things work?
This code:
.click( SetCheckBox1State(this.checked) );
Assigns the .click() function to be the output of this function: SetCheckBox1State(this.checked).
You will have to get rid of the argument (make it internal) and just pass the function name:
.click( SetCheckBox1State );

roll-over script not working

I am trying to make a mouse roll-over. i.e when user places the pointer on the image mouse over event is triggered and the next image from the array comes over.But nothing is happening when i am running this script :
window.onload = startRollOver;
var pictures = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg");
var i = 0;
function startRollOver() {
document.getElementById("picture").src.onmouseover = createRollOver();
}
function createRollOver() {
if(i<=7)
return pictures[i++];
if(i>7) {
i=0;
return pictures[i];
}
}
Where am i going wrong ?
.src.onmouseover does not make much sense. You should assign a function to onmouseover so that the function gets called when the mouse moves over the element:
document.getElementById("picture").onmouseover = function() { // is executed when mouse is over element
this.src = createRollOver(); // each time it is called, change the src
};
Also, you can use a more convenient way of declaring arrays:
["1.jpg", "2.jpg", ...]
You're setting "onmouseover" on the string "src" instead of on the DOM element. You need to set the event on the DOM element.
window.onload=startRollOver;
function startRollOver() {
document.getElementById("picture").onmouseover = function (e) {
e.target.src = createRollOver();
};
}
function createRollOver() {
// ...
}

Categories