I've been trying to fix this for hours now and just can't get it to work. I'm retrieving the name of every activity in the database and for every row it recreates this script with the correct data.
<script>var count = 1;</script>
#foreach($data as $scriptdata)
<script>
eval("var id" + count + " = '{{$scriptdata->activiteit}}';");
eval("var clas" + count + " = '{{$scriptdata->activiteit}}';");
eval("var id" + count + " = id" + count .replace(/[^a-zA-Z]/g, '') + ";");
eval("var clas" + count + " = clas" + count .replace(/[^a-zA-Z]/g, '') + ";");
$("#" + id1).mouseenter(function(event) {
console.log("clicked.");
var target = $('.' + clas1);
if( target.length ) {
$('html, body').animate({
scrollTop: target.offset().top-120
}, 1000);
}
});
count++
</script>
#endforeach
the variables become dynamic without any trouble, I just can't get that .replace to do it's job.
anyone?:p
Either output the variables from the serverside code, use Objects with bracket notation, use common classes so there is no need to have individual selections, or make it so the variables are not in global scope.
Make it so the variable are not in global scope
(function() {
var id = '{{$scriptdata->activiteit}}';
var clas = '{{$scriptdata->activiteit}}';
$("#" + id).mouseenter(function(event) {
var target = $('.' + clas);
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - 120
}, 1000);
}
});
}());
Now you do not have to worry about count.
Related
I have some JavaScript that currently looks for _target and anchors to target.
I wish to change it to look for a array [_target_index] however I cant seem to get this to work every time I try I get errors.
When I console.log my array I get my expected array output.
Can someone help me addend y code to accept the array rather than just _target ?
What I tried
_scrollTopPixels = (anchorElementArray [_target_index]).offset().top - (_fixedNavHeight + _pdpNavigationHeight + _pdpSectionsHeight);
console error
Uncaught TypeError: anchorElementArray[_target_index].offset is not a function
My full code
_pdpNavigationScrollTo = function () {
_pdpLink.on('click', function (e) {
e.preventDefault();
var _fixedNavHeight, _target, _target_index, _scrollTopPixels;
if (!INFORMA.global.device.isDesktop) {
_target = $(this).data('target');
_target_index = $(this).data('target-index');
$('#pdp-sections').slideUp();
_pdpNavigationHeight = $('#pdp-navigation .nav-pdp-nondesktop').outerHeight();
if (!_pdpFixed)
_pdpSectionsHeight = $('#pdp-sections').height();
else
_pdpSectionsHeight = 0;
_fixedNavHeight = _navHeightMobile;
var anchorElementArray = $("[id='" + _target + "']");
console.log(anchorElementArray[_target_index]);
if (anchorElementArray.length >= [_target_index]) {
//_scrollTopPixels = $("#" + _target).offset().top - (_fixedNavHeight + _pdpNavigationHeight + _pdpSectionsHeight);
_scrollTopPixels = (anchorElementArray [_target_index]).offset().top - (_fixedNavHeight + _pdpNavigationHeight + _pdpSectionsHeight);
} else {
_scrollTopPixels = $("#" + _target).offset().top - (_fixedNavHeight + _pdpNavigationHeight + _pdpSectionsHeight);
}
$('html, body').stop().animate({
scrollTop: _scrollTopPixels
}, 1000);
} else {
_target = $(this).data('target');
$('#pdp-navigation li').removeClass('selected');
$('#pdp-navigation li').addClass('select-options');
_pdpNavigationHeight = _pdpNavigation.height();
_fixedNavHeight = _navHeight;
_scrollTopPixels = $("#" + _target).offset().top - (_fixedNavHeight + _pdpNavigationHeight);
$('html, body').stop().animate({
scrollTop: _scrollTopPixels
}, 1000);
}
})
};
The jQuery method offset requires a jQuery object to access it, as such you need to change;
(anchorElementArray[_target_index]).offset().top
to
$(anchorElementArray[_target_index]).offset().top
below is the js code for wikipedia search project. I am getting infinite for loop even though it had condition to stop repeating the loop. I am stuck in this problem.
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
for (i = 1; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
You are appending to each and every one of <p> in page.
Since your for loop appends even more <p> (and you possibly have a high number of <p> elements in your page beforehand) you overflow your call stack.
You probably wanted to append to a specific <p>. Try giving an id to your selector.
from what i can see in the url you need to do the following:
loop over the terms found and select the link based on the index of the element, chose a single element .contentto append the data not a set of elements p, this will increase the number of duplicated results
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search='+srcv+'&format=json&limit=20&callback=?', function(json){
$.each(json[1],function(i,v){
$('.content').append("<p><a href ='"+json[2][i]+"'target='_blank'>"+json[0]+"</a>"+v+"</p>");
});
});
see demo: https://jsfiddle.net/x79zzp5a/
Try this
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
var i = 1;
for (i; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
this code works:
var myElement = document.getElementById("red");
setInterval(function() {
console.log("Left:" + myElement.offsetLeft + "px | Top:" + myElement.offsetTop + "px");
}, 1000);
This prints out the position(x, y) every second
But If I try and change it to using objects:
function Enemy(id){
this.id = getElementById(id);
this.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + this.id.offsetLeft + "px | Top:" + this.id.offsetTop + "px");
}, 1000);
}
}
$(document).ready(function(){
var enemy = new Enemy("red");
enemy.getCoordinates();
});
It prints out nothing - and I can't see where my mistake is.
In a setInterval or setTimeout (or any event handler like onclick) the this variable refers to the global object. In a browser that's window.
In modern browsers you can do this:
setInterval((function() {
console.log("Left:" + that.id.offsetLeft + "px");
}).bind(this), 1000); // <------- bind
Otherwise all other solutions are basically similar to your first piece of code.
Note that there is an implementation of bind() in pure js from Mozilla that can be ported to older browsers. Search for it on MDN.
The problem is that the value of "this" is changing within the setInterval. The fix is to change it to:
function Enemy(id){
this.id = document.getElementById(id);
var self = this;
this.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + self.id.offsetLeft + "px | Top:" + self.id.offsetTop + "px");
}, 1000);
}
}
function Enemy(id){
this.id = document.getElementById(id);
this.getCoordinates = function(){
var element = this.id;
setInterval(function() {
console.log("Left:" + element.offsetLeft + "px | Top:" + element.offsetTop + "px");
}, 1000);
}
}
$(document).ready(function(){
var enemy = new Enemy("red");
enemy.getCoordinates();
});
As slebetman said, the 'this' variable is not what you expected. Try saving it in a 'that' variable, which can be accessed in different scopes.
function Enemy(id){
var that = this; // reference to 'this' that can be used in other scopes
that.id = document.getElementById(id);
that.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + that.id.offsetLeft + "px | Top:" + that.id.offsetTop + "px");
}, 1000);
}
return that;
}
I have a bit of code that searches the current information shown on the page from a input source, which is an XML loaded in. This then shows how many times the word has been found, it should then display the lines where the word was found although currently it is showing all the lines. The code is
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", g_playDOM).each(
function() {
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query,
'<span class="query_match">' + query + '</span>');
if (currentLine.search(regex_query) > 0)
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
});
$("#sideInfo").append(
"<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
$(document).ready(function() {
loadPlay();
$("#term_search").focus(function(event) {
$(this).val("");
});
$("#term_search").keypress(function(event) {
if (event.keyCode == 13)
searchResults($("#term_search").val());
});
$('#term-search-btn').click(function() {
searchResults($("#term_search").val());
});
});
</script>
Currently the number of lines the word is on is being shown correctly.
If you want a line of code to be executed within a conditional, then you need to place curly braces around it. Otherwise, only the very next action item will be executed. In your case, increase the count of the number of lines that match.
Your subsequent action item, appending the found line into the DOM is executed on every branch because the if statement has already done its job. Offending lines below:
if ( currentLine.search(regex_query) > 0 ) num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
Fixed:
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
}
I type in scroll(0,10,200,10);
But when it runs it passes the string "xxpos" or "yypos" and I did try it without the appostraphes, but it just didn't work.
scroll = function(xpos,ypos,time,rounds){
var xxpos = xpos*1;
var yypos = ypos*1;
var rrounds = rounds*1;
var ttime = time*1;
x = 0;
xyz=window.setInterval("scroller('xxpos','yypos','ttime','rrounds')",ttime);
}
function scroller(xpos,ypos,time,rounds){
alert(xpos + ypos + time + rounds);
}
Don't use strings, use closures (anonymous functions).
window.setTimeout(function() {
scroller(xxpos, yypos, ttime, rrounds);
}, ttime);
It should be like this:
xyz=window.setInterval("scroller(" + xxpos + "," + yypos + "...
otherwise you just pass strings xxpos, yypos etc.
do you happen to know that in your code, each call to scroll() builds a timer?
do you mean to do it like it was a loop? then:
xyz = window.setTimeout(function(){
scroller(xxpos,yypos,ttime,rrounds)
},ttime);
You should use closure:
...
xyz = window.setInterval(function() { scroller(xxpos,yypos,ttime,rrounds); }, ttime);
...
That's because the string does not become the variable.
This would work:
window.setInterval("scroller("+ xxpos + "," + yypos + "," + ttime + "," + rrounds + ")",ttime);
Or better:
window.setInterval(function() { scroller(xxpos, yypos, ttime, rrounds); }, ttime);