Im trying to add some callback to my code, so when clicking on a picture outside the map, the maps get centered to the position that image contains, so I try this.
Gmaps4Rails.callback = function() {
var event = document.getElementsByClassName("link-s");
event.onclick = showEvent;
function showEvent(pos) {
var pos = -25.363882,131.044922;
Gmaps4Rails.map.setCenter(pos.latLng);
};
};
it doesnt throw any error, im using "pos" for testing purposes, but i cant make it work.
It's just a question of javascript:
Gmaps4Rails.callback = function() {
var events = document.getElementsByClassName("link-s");
for (var i = 0; i < events.length; ++i) {
events[i].onclick = function() { showEvent(); };
}
function showEvent() {
Gmaps4Rails.map.setCenter(new google.maps.LatLng(-25.363882,131.044922));
};
}
Related
I have the following situation which I cannot solve. I am relatively new to js. I have a js that runs on a webpage. The script runs when a KB shortcut is pressed. After modifying a few things, it pops up an html banner in which I want to put certain messages and buttons depending on what thing the user ran a script on. For a simple case, let's say there are two potential messages that can go in this popup. I have the details in an object array:
NH_Bann = {
STC: {
active: false,
bannText: "Force Title Case: ",
id: "toTitleCaseStrong",
value: "Yes",
action: function() {
var newNameStr = toTitleCaseStrong(vname);
if (newNameStr !== name) {
//**update function
NH_Bann.STC.active = false;
}
}
},
DTC: {
active: false,
bannText: "Enable DTC? ",
id: "addDTC",
value: "Yes",
action: function() {
//**update function
NH_Bann.DTC.active = false;
}
}
}
When the script is run, there are some if statments that can change the active keys to true. After the script runs, I want to run through the objects in NH_Bann, and if the active key is true, make a message with an action button that fires the action button. The part I am having trouble with is making the buttons dynamically. From other threads, I thought I could store the buttons in an array, but maybe the onclick doesn't work that way? This is what I have:
function setupButtons() {
var ixButt = 0;
var btn = [];
for (var NHix = 0; NHix < Object.keys(NH_Bann).length; NHix++ ) {
tempKey = Object.keys(NH_Bann)[NHix];
if (NH_Bann[tempKey].active) {
btn[ixButt] = document.getElementById(NH_Bann[tempKey].id);
btn[ixButt].onclick = function(){
NH_Bann[tempKey].action();
assembleBanner(); // makes the html for the banner
}
ixButt++;
}
}
}
I make the buttons in another piece of code which sets up the ids:
function assembleBanner() {
sidebarMessageEXT = [sidebarMessage.slice(0)];
var EXTOption = false;
for (var NHix = 0; NHix < Object.keys(NH_Bann).length; NHix++ ) {
tempKey = Object.keys(NH_Bann)[NHix];
if (NH_Bann[tempKey].active) {
sidebarMessageEXT.push(NH_Bann[tempKey].bannText + '<input id="' + NH_Bann[tempKey].id + '" type="button" value="' + NH_Bann[tempKey].value + '">');
EXTOption = true;
}
}
if (EXTOption) {
sidebarMessageEXT = sidebarMessageEXT.join("<li>");
displayBanners(sidebarMessageEXT,severity);
setupButtons();
} else {
displayBanners(sidebarMessage,severity);
setupButtons();
}
}
The issue i'm having is that I get the two distinct messages and two buttons in the banner if both objects are active==true, but pressing them always fires the update function of the DTC object. Any suggestions? I'm open to other methods, but I need to be able to add to the object list over time and have the buttons be displayed conditionally on the status of the active key for each object. Thx!
The problem has to do with closures. In this code:
function setupButtons() {
var ixButt = 0;
var btn = [];
for (var NHix = 0; NHix < Object.keys(NH_Bann).length; NHix++ ) {
tempKey = Object.keys(NH_Bann)[NHix];
if (NH_Bann[tempKey].active) {
btn[ixButt] = document.getElementById(NH_Bann[tempKey].id);
btn[ixButt].onclick = function(){
NH_Bann[tempKey].action();
assembleBanner(); // makes the html for the banner
}
ixButt++;
}
}
}
...tempKey is a variable that lives within the call to setupButtons. Notice that you're creating two onclick function callbacks in a loop, and both make reference to tempKey. However, they're not going to be referencing the variable's value at the time of function creation, but rather the latest value of the variable. So once the loop completes, tempKey is going to reference the last value it had.
To work around this, you can use this trick to create a new closure for each onclick that will have the correct value:
function setupButtons() {
var ixButt = 0;
var btn = [];
for (var NHix = 0; NHix < Object.keys(NH_Bann).length; NHix++ ) {
tempKey = Object.keys(NH_Bann)[NHix];
if (NH_Bann[tempKey].active) {
btn[ixButt] = document.getElementById(NH_Bann[tempKey].id);
btn[ixButt].onclick = (function(buttonId) {
return function() {
NH_Bann[buttonId].action();
assembleBanner(); // makes the html for the banner
}
})(tempKey);
ixButt++;
}
}
}
Essentially, this is binding the current value of tempKey to a new variable by passing it to an immediately-executing function, so both onclick functions no longer reference the variable which changes during the loop.
For a less esoteric way to do this, you could move the creation of each button into its own named function, passing the required data:
function setupButtons() {
var btn = [];
for (var NHix = 0; NHix < Object.keys(NH_Bann).length; NHix++) {
tempKey = Object.keys(NH_Bann)[NHix];
if (NH_Bann[tempKey].active) {
btn.push(setupButton(NH_Bann[tempKey]);
}
}
}
function setupButton(bannerData) {
var button = document.getElementById(bannerData.id);
button.onclick = function() {
bannerData.action();
assembleBanner();
};
return button;
}
We ask the user here to define html, so add a div or a section or something like that. So, I want the validation-tooltips when editing my HTML. But don't wanna have the doc-type warning.
Try this
var session = editor.getSession();
session.on("changeAnnotation", function() {
var annotations = session.getAnnotations()||[], i = len = annotations.length;
while (i--) {
if(/doctype first\. Expected/.test(annotations[i].text)) {
annotations.splice(i, 1);
}
}
if(len>annotations.length) {
session.setAnnotations(annotations);
}
});
With "Unexpected End of File. Expected DOCTYPE." warning filtered.
var session = editor.getSession();
session.on("changeAnnotation", function () {
var annotations = session.getAnnotations() || [], i = len = annotations.length;
while (i--) {
if (/doctype first\. Expected/.test(annotations[i].text)) {
annotations.splice(i, 1);
}
else if (/Unexpected End of file\. Expected/.test(annotations[i].text)) {
annotations.splice(i, 1);
}
}
if (len > annotations.length) {
session.setAnnotations(annotations);
}
});
If instead you operate on the annotations directly and call the editor onChangeAnnotation method directly to update the annotations on the page you can prevent firing another changeAnnotation event and calling this event handler twice as Chris's answer does.
var editor = Application.ace.edit(element),
session = editor.getSession();
session.on('changeAnnotation', function () {
session.$annotations = session.$annotations.filter(function(annotation){
return !(/doctype first\. Expected/.test(annotation.text) || /Unexpected End of file\. Expected/.test(annotation.text))
});
editor.$onChangeAnnotation();
});
Im trying to pause a timed slideshow when you're hovering over a div
<div id="play_slide" onMouseOver="clearTimeout(playTime)"></div>
If i put onMouseOver="clearTimeout(playTime)" inside an li on the page, it'll pause, so I know my code is correct, it just wont work on the div! Also if i get rid of the id, it will alert when i put an alert function into an event handler
This is the js.
var playTime;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
you can see this here: www.nicktaylordesigns.com/work.html
I would do it like this:
( and no inline script... just <div id="play_slide">Something</div> )
var playTime;
var indexPlay = 0;
var slideElement;
window.onload = function () {
slideElement = document.getElementById("play_slide");
slideElement.addEventListener('mouseenter', function () {
console.log('stop');
clearTimeout(playTime);
});
slideElement.addEventListener('mouseleave', function () {
console.log('continue');
playTime = setTimeout(playSlide, 2500);
});
playSlide();
}
function playSlide() {
var slideshow = slideElement.style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if (indexPlay > images.length - 1) {
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/" + images[indexPlay] + ".png')";
playTime = setTimeout(playSlide, 2500);
}
Fiddle
This issue is related to the script loading. Your script gets loaded after the DOM is processed so function doesn't get attached to the event.
If you are using jQuery then you can use below code.
$(function () {
$("#play_slide").mouseover(function(){
var playTime = 33;
clearTimeout(playTime);
});
});
If you don't want to use JQuery then you can do the same thing in JavaScript as below.
window.onload = function(){
document.getElementById("play_slide").onmouseover = function(){
var playTime = 33;
clearTimeout(playTime);
};
}
I got it! the div tag was somehow broken, I coded a div around it and gave it the event handlers and a class. That worked, then i simply changed the class to an id and got rid of the original div. Idk what was going on but it works now. Thanks for your suggestions!
Can you try this,
<div id="play_slide" onmouseover="StopSlide();">Stop</div>
<script>
var playTime;
var indexPlay;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
function StopSlide(){
window.clearTimeout(playTime);
}
playSlide();
</script>
I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:
How to I undo .detach()?
But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:
function MMtoggle(IDnum) {
var rowID = "row" + IDnum;
var jRow = '#' + rowID;
thisMMbtn = $(jRow).find(".addMMbtn");
var light = false;
var that = this;
if (light == false) {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
$(this).unbind("click");
light = true;
}
);
}
else {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
thisMM = thisRow.find(".mmCell");
SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
$(this).unbind("click");
light = false;
}
);
}
}
MMtoggle(g.num);
A fiddle of the problem is here: http://jsfiddle.net/pScJc/
(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)
Looking at your code I don't think so you need detach for what you are trying to achieve.
Instead try this code.
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var $mmCell = thisTxt.find('.mmCell');
if($mmCell.length == 0){
$mmCell = $('<div class = "mmCell prep"></div>')
.appendTo(thisTxt).hide();
}
$mmCell.toggle();
//$(this).unbind("click");
}
);
Demo
I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.