JS variable equal to html data attribute - javascript

I'm trying to create a variable in my Javascript that uses the value assigned on data-start-time.
Here is my html:
<li data-pile="1" id="kQKhpVWBjoQ" data-start-time="20" class="md-trigger md-setperspective">
</li>
Here is my JS:
function playVideo(videoId, cb) {
if(videoId) {
myModal.find('.md-video').append($videoDiv);
myModal.addClass('md-show');
setTimeout(function () {
console.log('#### id', videoId);
var startTime = videoId.getAttribute('data-start-time');
player.loadVideoById({'videoId': videoId, 'startSeconds': startTime});
player.videoEnded = function () {
cb && cb();
};
player.waitForChanges();
}, 1000);
}
}
If I create variable startTime and hardcode some value in my js the player works. However I
can seem to figure out what is wrong with line:
var startTime = videoId.getAttribute('data-start-time');
All I need to do is get the value assigned in html inside data-start-time="..." for each
"li" using the ids that vary according to the specific "li"

Try this:
var startTime = $('#'+videoId).prop('data-start-time');
Assuming what the function in receiving in videoId is a element ID then you need to get that element by the ID. Just naming the ID will not do it. You can also use plain javascript like this:
document.getElementById(videoId).getAttribute('data-start-time');

Related

Get data attr value on hover

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.

Jquery: how can I store a variable inside a function, and use it outside?

I am trying to change a text according to a mouse hover event:
$(document).ready(function() {
$('.blog_post_container').hover(function() {
var title = $(this).find('.blog_title').text();
$(this).find('.blog_title').text("READ MORE >");
}, function() {
$(this).find('.blog_title').text(title);
}
});
In the HTML: div.blog_title is inside div.blog_post_container.
The variable "title" was created inside the function called on mouse hover to store the blog title of that specific blog post. The idea was to use it later, when the mouse leaves the blog_post_container, but I cannot use it outside the function where it was created.
I cannot either create the variable before that function, because it will always return the title of the first blog post.
I know the solution is simple, but I'm just not finding it. Any help is appreciated!
Store the title like this:
$(this).data('blog-title', title);
You can then retrieve it later with just a reference to the element:
var title = $('.blog_post_container').data('blog-title');
.data() API
Remove var to attach variable to window object
title = $(this).find('.blog_title').text();
It's better if you define it before the document ready
var title;
//document ready code
Maybe an overly complicated solution:
function rollOver(oElem, tHoverText){
this.tHover=tHoverText;
this.oElem=oElem;
this.init()
};
rollOver.prototype.init = function() {
this.oTitle = this.oElem.querySelector('.blog_title');
this.tTitle = this.oTitle.innerHTML;
this.initEvents();
};
rollOver.prototype.initEvents = function() {
var self = this;
this.oTitle.addEventListener('mousehover', this.changeTitle.bind(this), false);
this.oTitle.addEventListener('mouseout', this.restoreTitle.bind(this), false);
};
rollover.prototype.changeTitle = function() {
var self = this;
this.oTitle.innerHTML = self.tHover;
};
rollover.prototype.restoreTitle = function() {
var self = this;
this.oTitle.innerHTML = self.tTitle;
};
You can use it like this:
var blogPost = document.getElementsByClassName('blog_post_container')[0];
var b = new rollOver(blogPost, "Read more");
To retrieve the title text, use b.tTitle.

How to have multiple instances of a jQuery plugin

I am trying to create a SoundCloud music player. It can play any track from SoundCloud, but this plugin is only working if there is only one instance of it in the page. So it wont work if two of the same plugin are in the page.
Here is an example of having two players in the page: JSFiddle
var trackURL = $(".player").text();
$(".player").empty();
$(".player").append("<div class='playBTN'>Play</div>");
$(".player").append("<div class='title'></div>");
var trackId;
SC.get('/resolve', { url: trackURL }, function (track) {
var trackId = track.id;
//var trackTitle = track.title;
$(".title").text(track.title);
$(".playBTN").on('click tap', function () {
//trackId = $(".DSPlayer").attr('id');
stream(trackId);
});
// first do async action
SC.stream("/tracks/" + trackId, {
useHTML5Audio: true,
preferFlash: false
}, function (goz) {
soundToPlay = goz;
sound = soundToPlay;
scTrack = sound;
//updater = setInterval( updatePosition, 100);
});
});
var is_playing = false,
sound;
function stream(trackId) {
scTrack = sound;
if (sound) {
if (is_playing) {
sound.pause();
is_playing = false;
$(".playBTN").text("Play");
} else {
sound.play();
is_playing = true;
$(".playBTN").text("Pause");
}
} else {
is_playing = true;
}
}
If you remove any of these div elements that hold the .player class, the other element will work. So it only doesn't work because there are two instances of the same plugin.
How can I fix it? to have multiple instances of the player in one page?
I have identified the problem. It has to do with the fact that you are trying to load multiple tracks at the same time, but have not separated the code to do so.
As #Greener mentioned you need to iterate over the .player instances separately and execute a SC.get() for each one of them.
Here is what I see happening that is causing the problem:
var trackURL = $(".player").text();
^The code above returns a string that contains both of the URLs you want to use back-to-back without spaces. This creates a problem down the road because of this code:
SC.get('/resolve', { url: trackURL }, function (track) {...
That is a function that is trying to load the relevant song from SoundCloud. You are passing it a variable "trackURL" for it to try and load a specific URL. The function gets a string that looks like "URLURL" what it needs is just "URL".
What you can do is iterate over all the different ".player" elements that exist and then call the sounds that way. I modified your script a little to make it work using a for loop. I had to move the "empty()" functions into the for loop to make it work correctly. You have to use .eq(index) when referring to JQuery array of elements.
Like this:
var trackURL
var trackId;
for(index = 0; index < $(".player").length; index++){
trackURL = $(".player").eq(index).text();
//alert(trackURL);
$(".player").eq(index).empty();
$(".player").eq(index).append("<div class='playBTN'>Play</div>");
$(".player").eq(index).append("<div class='title'></div>");
SC.get('/resolve', { url: trackURL }, function (track) {
var trackId = track.id;
alert(track.id);
//var trackTitle = track.title;
$(".title").eq(index).text(track.title);
$(".playBTN").eq(index).on('click tap', function () {
//trackId = $(".DSPlayer").attr('id');
stream(trackId);
});
// first do async action
SC.stream("/tracks/" + trackId, {
useHTML5Audio: true,
preferFlash: false
}, function (goz) {
soundToPlay = goz;
sound = soundToPlay;
scTrack = sound;
//updater = setInterval( updatePosition, 100);
});
});
}
This is not a completely finished code here, but it will initiate two separate songs "ready" for streaming. I checked using the commented out alert what IDs SoundCloud was giving us (which shows that its loaded now). You are doing some interesting stuff with your streaming function and with the play and pause. This should give you a good idea on what was happening and you can implement your custom code that way.

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);
});

Categories