Home > Enterprise >  Issue with Javascript in Posting system
Issue with Javascript in Posting system

Time:01-11

So, I have a posting system. When you type a post in the input field and click the submit button, the post displays with the help of PHP and AJAX.

Now on that post are stuff like a like button and comment button, and when you click the like button, it turns blue. Now, after making a post and the post displaying, clicking the like button will make it blue. However, let's say you make another post. For that post, everything works, except when you click the like button on the second or third post, it makes the like button on the first post only turn blue, similarly with the comment button. Also, the first post has a background color of silver (#C0C0C0), however any other post, like the second or third post, don't. They have no background color.

This stuff (turning blue on click) is accomplished using JavaScript. What I identified from this is that the JS isn't working for any other post besides the first post. To resolve this, I tried changing the position of the JS in the code because I thought it had something to do with the scope, but it didn't. Please help, with the JS and the background color issue.

PHP/HTML/CSS Code:

<style>
.textPost {
  margin-top: 170px;
  width: 650px;
  height: 400px;
  position: fixed;
  background-color: #C0C0C0;
  margin-left: 685px;
  border-radius: 15px;
}

.textpostFormat {
  margin-left: -640px;
  position: fixed;
}
</style>

<div >
  <?php

  $sql = "SELECT * FROM posts";
  $result = mysqli_query($connection, $sql);
  if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {

  ?>
  <div  id="textpostFormat">
          <img src="img/pfp.png" alt="pfp" onclick="location.href='profile.php'" >
    <b><div ><?php echo $firstname . "&nbsp;" . $lastname ?></div></b>
    <img src="img/options.png" alt="textpostOptions" >
    <hr style="margin-top: 85px; width: 600px; position: fixed; margin-left: 663px; border:1px solid black; border-radius: 10px">
    <hr style="margin-top: 200px; width: 600px; position: fixed; margin-left: 663px; border:1px solid black; border-radius: 10px">
    <div  style="position: fixed">
      <hr style="margin-top: 250px; width: 600px; position: fixed; margin-left: 663px; border: 1px solid black; border-radius: 10px">
      <div >
        <div style="float: left; margin: 10px; cursor: pointer">1</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">2</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">3</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">4</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">5</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">6</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">7</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">8</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">9</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin-left: 275px; cursor: pointer; margin-top: 10px; position: fixed">10</div>
      </div>
    </div>
    <hr style="margin-top: 320px; width: 600px; position: fixed; margin-left: 663px; border: 1px solid black; border-radius: 10px">
    <img src="img/pfp.png" alt="commentpfp" onclick="location.href='profile.php'" >
    <input type="text" name="textComment"  id="textComment" placeholder="Write a comment">
    <p style="margin-left: 670px; margin-top: 95px; position: fixed; font-size: 45px; font-family: 'Rajdhani'"><?php echo $row["body"]; ?></p>
    <div  style="position:fixed; font-family: 'Rajdhani'; margin-left: 820px; margin-top: 150px">
      <h4 id="textDataLikes" style="cursor: pointer">0 Likes</h4>
      <h4 id="textDataComments" style="margin-left: 102px; margin-top: -42px; cursor: pointer">0 Comments</h4>
      <h4 id="textDataReactions" style="margin-left: 240px; margin-top: -42px; cursor: pointer">0 Reactions</h4>
    </div>
    <div style="margin-left: 715px; position: fixed; font-family: 'Rajdhani'">
      <h2 style="margin-top: 206px; margin-left: -30px; cursor:pointer; padding: 5px; position: fixed"  id="textLike" onclick="textLikeClick()"><i ></i> Like</h2>
      <h2 style="margin-left: 99px; margin-top: 206px; cursor:pointer; padding: 5px; position: fixed"  id="makeComment" onclick="textCommentClick()"><i  style="margin-top: 2px;"></i> Comment</h2>
      <h2 style="margin-left: 290px; margin-top: 206px; cursor:pointer; padding: 5px; position: fixed"  id="textReact"><i  style="margin-top: 2px;"></i> React</h2>
      <h2 style="margin-left: 432px; margin-top: 206px; cursor:pointer; padding: 5px; position: fixed"  id="textShare"><i  style="margin-top: 2px"></i> Share</h2>
    </div>
  </div>
  <div style="margin-left: 398px; margin-top: 236px">
    <img  id="textUpvoteImg" src="img/upvote.png" alt="upvote" onclick="changetextUpvote()" style="width: 100px; margin-bottom: 28px; cursor: pointer">
    <img  id="textDownvoteImg" src="img/downvote.png" alt="downvote" onclick="changetextDownvote()" style="width: 55px; margin-top: 32px; margin-left: 21px; position: fixed; cursor: pointer">
  </div>
  <?php

  }
}

  ?>
  </div>
  <?php

  }
}

  ?>
</div>

AJAX code (to display posts without page refresh):

function makePost() {
  var postContent = $("#postContent").val();
  if (postContent.length > 0) {
    jQuery.ajax({
      url:"yourposts.php",
      data:{
        postContent: postContent
      },
      type:"POST",
      success:function(data){
        if (data == "success") {
          $("#textpostFormat").html(postContent);
        }
      }
    });
  }
}

Javascript code (for turning like button blue and stuff):

<script type="text/javascript">

function changetextUpvote() {
  var textUpvoteImg = document.getElementById('textUpvoteImg');
  if (textUpvoteImg.src.match("orangeupvote")) {
    textUpvoteImg.src = "img/upvote.png";
  } else {
    textUpvoteImg.src = "img/orangeupvote.png";
    textDownvoteImg.src = "img/downvote.png";
  }
}

function changetextDownvote() {
  var textDownvoteImg = document.getElementById('textDownvoteImg');
  if (textDownvoteImg.src.match("orangedownvote")) {
    textDownvoteImg.src = "img/downvote.png";
  } else {
    textDownvoteImg.src = "img/orangedownvote.png";
    textUpvoteImg.src = "img/upvote.png";
  }
}

function textLikeClick() {
  document.getElementById('textLike').style.color = "blue";
}

function textCommentClick() {
  document.getElementById('textComment').focus();
}

</script>

CodePudding user response:

None of the elements here have an ID attribute. Identification of elements is done based upon inspecting the event.target and navigating around the DOM using querySelector, parentNode and perhaps other techniques such as nextElementSibling etc

The buttons all register a single eventlistener which forks logic based upon a data-set attibute.

document.querySelectorAll('[type="button"]').forEach(bttn=>bttn.addEventListener('click',function(e){
  
  let img=this.parentNode.querySelector('img');
  let text=this.parentNode.querySelector('textarea');
  
  switch(this.dataset.action){
    case 'upvote':
      img.src='img/orangeupvote.png';
      img.classList.toggle(this.dataset.action)
    break;
    case 'downvote':
      img.src='img/orangedownvote.png';
      img.classList.toggle(this.dataset.action)
    break;
    case 'comment':
      text.focus();
      
      let fd=new FormData();
          fd.set('comment',text.value);
          
      fetch('yourposts.php',{method:'post',body:fd})
          .then(r=>r.text())
          .then(text=>{alert(text)})
    break;
    case 'like':
      this.classList.toggle('liked')
    break;
  }
}));
.liked{background:blue;color:white}
textarea:focus{background:pink}
.upvote{outline:2px solid green}
.downvote{outline:2px solid red}
<div >
  <!--
  <?php

    $sql = "SELECT * FROM posts";
    $result = mysqli_query($connection, $sql);
    if (mysqli_num_rows($result) > 0) {
      while ($row = mysqli_fetch_assoc($result)) {

  ?>
 -->
  <h1>Example data</h1>
  <div >
    <p>Lorem ipsum dolor solit...etc #1</p>
    <img />
    <input type='button' class='usr-interaction' data-action='upvote' value='Upvote' />
    <input type='button' class='usr-interaction' data-action='downvote' value='Downvote' />
    <textarea cols=50 rows=5>This is simply a comment...</textarea>
    <input type='button' class='usr-interaction' data-action='comment' value='Comment' />
    <input type='button' class='usr-interaction' data-action='like' value='Like' />
  </div>

  <div >
    <p>Lorem ipsum dolor solit...etc #2</p>
    <img />
    <input type='button' class='usr-interaction' data-action='upvote' value='Upvote' />
    <input type='button' class='usr-interaction' data-action='downvote' value='Downvote' />
    <textarea cols=50 rows=5>Also a simple comment...</textarea>
    <input type='button' class='usr-interaction' data-action='comment' value='Comment' />
    <input type='button' class='usr-interaction' data-action='like' value='Like' />
  </div>
  
  <div >
    <p>Lorem ipsum dolor solit...etc #3</p>
    <img />
    <input type='button' class='usr-interaction' data-action='upvote' value='Upvote' />
    <input type='button' class='usr-interaction' data-action='downvote' value='Downvote' />
    <textarea cols=50 rows=5>Guess what this is...</textarea>
    <input type='button' class='usr-interaction' data-action='comment' value='Comment' />
    <input type='button' class='usr-interaction' data-action='like' value='Like' />
  </div>





</div>

CodePudding user response:

Stripping all the hideous inline styles and replacing ID attributes with, in this case, simply data-id attributes to yield some example rendered markup like this below. This is NOT intended to be a final solution for you - you need to understand how you fit your functions within this because quite frankly the code given is chaotic.

within the click handler function if you supply the event as an argument to the function you can access event.target within the function. That event.target points to the element that initiated the click. From that point you can use DOM navigation techniques to find other nodes of interest.

document.querySelectorAll('.textpostFormat *[data-id]').forEach(n=>n.addEventListener('click',function(e){
  switch( this.dataset.id ){
    case 'textUpvoteImg':
      changetextUpvote(e);
    break;
    case 'textDownvoteImg':
      changetextDownvote(e)
    break;
    case 'makeComment':
      textCommentClick(e);
    break;
    case 'textLike':
      textLikeClick(e);
    break;
  }
}));



function changetextUpvote(e) {
    alert(e.target)
}

function changetextDownvote(e) {
  alert(e.target)
}

function textLikeClick(e) {
  alert(e.target)
}

function textCommentClick(e) {
  alert(e.target)
}
<div class='textpostFormat'>
    <a href='profile.php'><img src='img/pfp.png' alt='pfp' class='textpostPFP'></a>
    <div class='textinfo'><b>FIRSTNAME LASTNAME #1</b></div>
    <img src='img/options.png' class='textpostOptions' />

    <div class='textfeedbackBar'>
        <div class='textratingBar'>
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div>5</div>
            <div>6</div>
            <div>7</div>
            <div>8</div>
            <div>9</div>
            <div>10</div>
        </div>
    </div>

    <a href='profile.php'><img src='img/pfp.png' alt='commentpfp' class='textcommentPFP' /></a>
    <input type='text' name='textComment' class='textComment' data-id='textComment' placeholder='Write a comment' />

    <p>PARAGRAPH - BODY CONTENT #1</p>
    <div class='textPostData'>
        <h4 data-id='textDataLikes'>0 Likes</h4>
        <h4 data-id='textDataComments'>0 Comments</h4>
        <h4 data-id='textDataReactions'>0 Reactions</h4>
    </div>
    <div>
        <h2 class='textLike' data-id='textLike'><i class='fa fa-thumbs-up'></i> Like</h2>
        <h2 class='makeComment' data-id='makeComment'><i class='fa fa-comment' style='margin-top: 2px;'></i> Comment</h2>
        <h2 class='textReact' data-id='textReact'><i class='fa fa-smile' style='margin-top: 2px;'></i> React</h2>
        <h2 class='textShare' data-id='textShare'><i class='fa fa-share' style='margin-top: 2px'></i> Share</h2>
    </div>
    <div>
        <img class='textupvote' data-id='textUpvoteImg' src='img/upvote.png' alt='upvote' />
        <img class='textdownvote' data-id='textDownvoteImg' src='img/downvote.png' alt='downvote' />
    </div>
</div>


<div class='textpostFormat'>
    <a href='profile.php'><img src='img/pfp.png' alt='pfp' class='textpostPFP'></a>
    <div class='textinfo'><b>FIRSTNAME LASTNAME #2</b></div>
    <img src='img/options.png' class='textpostOptions' />

    <div class='textfeedbackBar'>
        <div class='textratingBar'>
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div>5</div>
            <div>6</div>
            <div>7</div>
            <div>8</div>
            <div>9</div>
            <div>10</div>
        </div>
    </div>

    <a href='profile.php'><img src='img/pfp.png' alt='commentpfp' class='textcommentPFP' /></a>
    <input type='text' name='textComment' class='textComment' data-id='textComment' placeholder='Write a comment' />

    <p>PARAGRAPH - BODY CONTENT #2</p>
    <div class='textPostData'>
        <h4 data-id='textDataLikes'>0 Likes</h4>
        <h4 data-id='textDataComments'>0 Comments</h4>
        <h4 data-id='textDataReactions'>0 Reactions</h4>
    </div>
    <div>
        <h2 class='textLike' data-id='textLike'><i class='fa fa-thumbs-up'></i> Like</h2>
        <h2 class='makeComment' data-id='makeComment'><i class='fa fa-comment' style='margin-top: 2px;'></i> Comment</h2>
        <h2 class='textReact' data-id='textReact'><i class='fa fa-smile' style='margin-top: 2px;'></i> React</h2>
        <h2 class='textShare' data-id='textShare'><i class='fa fa-share' style='margin-top: 2px'></i> Share</h2>
    </div>
    <div>
        <img class='textupvote' data-id='textUpvoteImg' src='img/upvote.png' alt='upvote' />
        <img class='textdownvote' data-id='textDownvoteImg' src='img/downvote.png' alt='downvote' />
    </div>
</div>

  •  Tags:  
  • Related